TAGS :Viewed: 9 - Published at: a few seconds ago

[ How to convert unicode to integer or float in dictionary in Python ]

For example, I have a dictionary, which is like:

Degree = {'Union': u'1', 'Cook': u'3', 'Champaign': u'7'}

How can I convert it as:

Degree = {'Union': 1, 'Cook': 3, 'Champaign': 7}

I know it's not a hard question, but I try many methods, like json, *.items... but I just do not get it.

Answer 1


Use a dictionary comprehension:

converted_degrees = {key: int(value) for (key,value) in Degree.items()}
>>> converted_degrees
{'Union': 1, 'Cook': 3, 'Champagne': 7}

Answer 2


Use int(value) to convert it :

values = {k:int(v) for(k,v) in Degree.items()}