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
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") .
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.
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.
dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
You can use a dictionary comprehension:
{k:int(v) for k, v in d.iteritems()}
where d
is the dictionary with the strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With