Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In dictionary, converting the value from string to integer

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
like image 631
Paarudas Avatar asked Feb 10 '12 07:02

Paarudas


People also ask

How do you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

Can dictionary values be int?

The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ). Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types.

How do I convert a string to a dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.


2 Answers

dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
like image 143
Amber Avatar answered Sep 18 '22 18:09

Amber


You can use a dictionary comprehension:

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

where d is the dictionary with the strings.

like image 42
jcollado Avatar answered Sep 19 '22 18:09

jcollado