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?
Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users.
The type casting process's execution can be performed by using two different types of type casting, such as implicit type casting and explicit type casting.
Type Casting Int to String We can use the str() function in python to convert a specified value or an object into a string object. The str in python takes three parameters in which one of them is required and the other two are optional. The object is any object or value(s) that is to be converted into a string object.
Python don't have any problem even if we don't declare the type of variable. It states the kind of variable in the runtime of the program. Python also take cares of the memory management which is crucial in programming. So, Python is a dynamically typed language.
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
This one liner will do it - but it does not check for type errors:
dicts1 = {'field1':'', 'field2':1, 'field3':1.2}
dicts2 = {'field1':123, 'field2':123, 'field3':'123'}
print {k : type(dicts1[k])(dicts2[k]) for k in dicts2}
This will also do it - and may be more readable for some:
print {k : type(dicts1[k])(v) for (k,v) in dicts2.iteritems()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With