How to Convert Dict Value to a Float

How to convert dict value to a float

Two things here: firstly s is, in effect, an iterator over the dictionary values, not the values themselves. Secondly, once you have extracted the value, e.g. by a for loop.The good news is you can do this is one line:

print(float([x for x in s][0]))

How to convert dict value to a float

Two things here: firstly s is, in effect, an iterator over the dictionary values, not the values themselves. Secondly, once you have extracted the value, e.g. by a for loop.The good news is you can do this is one line:

print(float([x for x in s][0]))

Converting python value of dictionary from list to float

Thanks for the answers.

This helped me realize that my main problem was the commas in the numbers.
I was able to remove the commas at the source with example.replace(',','',regex=True)

And then I was able to change the data type

convert_dict = {'column_name': int}
dataframe = dataframe.astype(convert_dict)

convert the value of dictionary from list to float

Your problem is in here: float(location[key][0,1])

# float objects are length 1
for key in location.keys():
location[key] = [float(location[key][0]),float(location[key][1])]
print location

How to use python dictionary values as integers, floats or booleans?

you could use a meta dictionary with key being the key of your dictionary and value would be the type to convert to, defaulting to convert as string if key not found:

meta_dict = { "Cat": int, "Food": float, "Enough": bool }
my_dict = { "Cat": "1", "Food": "1.5", "Enough": "True", "misc":"other" } # adding a string key for the demo

new_dict = { k:meta_dict.get(k,str)(v) for k,v in my_dict.items()}

print(new_dict)

prints:

{'Cat': 1, 'Food': 1.5, 'Enough': True, 'misc': 'other'}

if you don't have any string keys but only integers, floats and booleans, you could use ast.literal_eval to guess the type and convert to it:

import ast
my_dict = { "Cat": "1", "Food": "1.5", "Enough": "True" }
new_dict = { k:ast.literal_eval(v) for k,v in my_dict.items()}

In the future, save & reload your file as json so types are preserved.

How to convert all dict key from str to float

I suggest you to use a dictionary comprehension, which is easy to understand, as follows:

my_dict = { "123.23":10.50, "45.22":53, "12":123 }
my_dict = {float(i):j for i,j in mydict.items()}

print(my_dict) # {123.23: 10.5, 45.22: 53, 12.0: 123}


Related Topics



Leave a reply



Submit