1

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.

Wei-Ting Liao
  • 115
  • 2
  • 9

2 Answers2

3

Use a dictionary comprehension:

converted_degrees = {key: int(value) for (key,value) in Degree.items()}
>>> converted_degrees
{'Union': 1, 'Cook': 3, 'Champagne': 7}
jmduke
  • 1,657
  • 1
  • 13
  • 11
  • Thank you so so so much!!! It works now. I used to use for and if to distinguish the string and int then I failed many times. Again, Thank you so much. – Wei-Ting Liao Aug 02 '14 at 23:10
2

Use int(value) to convert it :

values = {k:int(v) for(k,v) in Degree.items()}
Ishan Garg
  • 178
  • 2
  • 11