首页 > 解决方案 > Changing String to Floating Point Number in Dictionary

问题描述

I am trying to convert a list made up of strings in a dictionary to float variables.

Here is the code I was given:

data = {'year':[1990, 2000, 2010], 'gdp':['8.95', '12.56', '14.78']}

The end result is supposed to look like this:

data = {'year':[1990, 2000, 2010], 'gdp':[8.95, 12.56, 14.78]}

Thank you in advance for any hints or help!

标签: pythondictionarytype-conversion

解决方案


This should do it:

data = {'year':[1990, 2000, 2010], 'gdp':['8.95', '12.56', '14.78']}
data['gdp'] = [float(string) for string in data['gdp']]

推荐阅读