Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 920
siva Avatar asked Mar 15 '11 19:03

siva


People also ask

Can you convert string to int or float?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

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

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

How do you convert values into a dictionary?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.


1 Answers

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")

like image 115
Powertieke Avatar answered Oct 07 '22 01:10

Powertieke