How to convert string values from a dictionary, into int/float datatypes?

152,905

Solution 1

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

Solution 2

Gotta love list comprehensions.

[dict([a, int(x)] for a, x in b.items()) for b in list]

(remark: for Python 2 only code you may use "iteritems" instead of "items")

Solution 3

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).

Solution 4

For python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Solution 5

If you'd decide for a solution acting "in place" you could take a look at this one:

>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]

Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.

Share:
152,905
siva
Author by

siva

junior engineer

Updated on July 09, 2022

Comments

  • siva
    siva almost 2 years

    I have a list of dictionaries as follows:

    list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
    

    How do I convert the values of each dictionary inside the list to int/float?

    So it becomes:

    list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ]
    

    Thanks.

  • Jim
    Jim about 13 years
    Haha, I was just changing that around, but yeah Jochen got it correctly, the whole naming your dictionary a list, confused me for a second.
  • siva
    siva about 13 years
    pretty hard to digest though agreed impressive! How to deal with: ValueError: empty string for float() for floating and ValueError: invalid literal for int() with base 10: '0.6' for 'integering'?
  • siva
    siva about 13 years
    eventually i wud like to do stats on the list items. (max, min, average, stdev)
  • Powertieke
    Powertieke about 13 years
    You could write a function to replace the int() call in the comprehention to allow for all of the exeptions you desire.
  • siva
    siva about 13 years
    could I edit the "v" on the spot if v='' , i.e. empty items? would try and see. thanks. helpful.
  • Powertieke
    Powertieke about 13 years
    Could be possible, but then i'd rather be using Perl :P
  • martineau
    martineau about 13 years
    Regarding your question about handling empty "v" items: you could rewrite the if expression to deal with them as I've shown in my revised answer.
  • martineau
    martineau about 13 years
    As to your second question about getting a syntax error at ... for k..., dictionary comprehensions require Python 2.7+ or 3.1+, so using earlier versions could be causing the problem.
  • martineau
    martineau about 13 years
    Follow up to my last comment: You could replace the int(x) in @Powertieke's answer with the conditional expression similar to what is in mine to get rid of the dictionary comprehension and result in something to use in earlier versions of Python.