convert string to integer in dictionary python 1

convert string to integer in dictionary python

# if you have string and integer
for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value) # use here str(value)

Here is what the above code is Doing:
1. Iterate over the list of dictionaries
2. Iterate over the key, value pairs in each dictionary
3. Try to convert the value to an integer
4. If that fails, convert the value to a float
5. If that fails, leave the value as a string

Similar Posts