How to convert string values from a dictionary, into int/float datatypes?
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.
Comments
-
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 about 13 yearsHaha, 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 about 13 yearspretty 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 about 13 yearseventually i wud like to do stats on the list items. (max, min, average, stdev)
-
Powertieke about 13 yearsYou could write a function to replace the int() call in the comprehention to allow for all of the exeptions you desire.
-
siva about 13 yearscould I edit the "v" on the spot if v='' , i.e. empty items? would try and see. thanks. helpful.
-
Powertieke about 13 yearsCould be possible, but then i'd rather be using Perl :P
-
martineau about 13 yearsRegarding 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 about 13 yearsAs 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 about 13 yearsFollow 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.