In a dictionary, converting a value from a string to an integer

Taking this example below:

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

I want to convert it to:

 'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5 
+13
python string dictionary integer
source share
4 answers
 dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems()) 
+14
source share

You can use dictionary comprehension:

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

where d is a dictionary with strings.

+11
source share
 >>> 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} 
+2
source share

So that someone does not mislead this page - dictionary literals in Python 2 and 3 can, of course, have numerical values ​​directly.

 embed={ 'the':1, 'cat':42, 'sat':2, 'on':32, 'mat':200, '.':4 } print(embed['cat']) # 42 
0
source share

All Articles