18

Taking this below example :

'user_stats': {'Blog': '1',
                'Discussions': '2',
                'Followers': '21',
                'Following': '21',
                'Reading': '5'},

I want to convert it into:

'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5
Amber
  • 507,862
  • 82
  • 626
  • 550
Paarudas
  • 375
  • 2
  • 4
  • 10

4 Answers4

20
dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
Amber
  • 507,862
  • 82
  • 626
  • 550
  • 10
    Note that [`iteritems`](https://docs.python.org/2/library/stdtypes.html#dict.iteritems) [is gone](http://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems) in [Python 3](https://www.python.org/download/releases/3.0/). Use [`items()`](https://docs.python.org/3.7/library/stdtypes.html#dict.items) instead. – patryk.beza Apr 16 '17 at 18:01
13

You can use a dictionary comprehension:

{k:int(v) for k, v in d.iteritems()}

where d is the dictionary with the strings.

jcollado
  • 39,419
  • 8
  • 102
  • 133
  • 2
    @IvanVirabyan You can also use dictionary comprehensions in python 2.7 since they have been backported. – jcollado Feb 10 '12 at 08:15
  • 2
    In fact, that code will only work in Python 2.7 . `dict.iteritems` is gone in 3, since `dict.items` no longer builds a list. – lvc Feb 10 '12 at 11:09
3
>>> d = {'Blog': '1', 'Discussions': '2', 'Followers': '21', 'Following': '21', 'Reading': '5'}
>>> dict((k, int(v)) for k, v in d.iteritems())
{'Blog': 1, 'Discussions': 2, 'Followers': 21, 'Following': 21, 'Reading': 5}
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

Lest anyone be mislead by this page - Dictionary literals in Python 2 and 3 can of course have numeric values directly.

embed={ 'the':1, 'cat':42, 'sat':2, 'on':32, 'mat':200, '.':4 }
print(embed['cat']) # 42
Pat Niemeyer
  • 5,930
  • 1
  • 31
  • 35