Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic type casting in python

Tags:

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?

like image 470
user1008636 Avatar asked Jul 12 '12 15:07

user1008636


People also ask

What are the two types of type casting in Python?

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.

How many types of casting are there in Python?

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.

Which command in Python is used for 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.

Does list support dynamic typing in Python?

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.


2 Answers

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
like image 145
Jon Clements Avatar answered Oct 19 '22 13:10

Jon Clements


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()}
like image 25
Maria Zverina Avatar answered Oct 19 '22 14:10

Maria Zverina