In dictionary, converting the value from string to integer

30,550

Solution 1

dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())

Solution 2

You can use a dictionary comprehension:

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

where d is the dictionary with the strings.

Solution 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}

Solution 4

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
Share:
30,550
Paarudas
Author by

Paarudas

Updated on December 02, 2020

Comments

  • Paarudas
    Paarudas over 3 years

    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
    
  • jcollado
    jcollado over 12 years
    @IvanVirabyan You can also use dictionary comprehensions in python 2.7 since they have been backported.
  • lvc
    lvc over 12 years
    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.
  • patryk.beza
    patryk.beza about 7 years
    Note that iteritems is gone in Python 3. Use items() instead.