Skip to content
Advertisement

Dynamic type casting in python

I have 2 dicts:

dicts1 = {'field1':'', 'field2':1, 'field3':1.2}
dicts2 = {'field1':123, 'field2':123, 'field3':'123'}

I want to convert each value in dict2 to be the same type as the corresponding value in dict1, what’s the quickest pythonic way of doing it?

Advertisement

Answer

Assuming they’re compatible types:

for k, v in dicts1.iteritems():
    try:
        dicts2[k] =  type(v)(dicts2[k])
    except (TypeError, ValueError) as e:
        pass # types not compatible
    except KeyError as e:
        pass # No matching key in dict
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement