I have 2 dicts:
JavaScript
x
3
1
dicts1 = {'field1':'', 'field2':1, 'field3':1.2}
2
dicts2 = {'field1':123, 'field2':123, 'field3':'123'}
3
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:
JavaScript
1
8
1
for k, v in dicts1.iteritems():
2
try:
3
dicts2[k] = type(v)(dicts2[k])
4
except (TypeError, ValueError) as e:
5
pass # types not compatible
6
except KeyError as e:
7
pass # No matching key in dict
8