首页 > 解决方案 > 将字典列表中的字符串更改为整数

问题描述

我的列表如下所示:

print(dataset[0:2])

这使:

[{'date': '13/09/2020', 'day': '13', 'month': '9', 'year': '2020', 'cases': '35', 'deaths': '0', 'countriesAndTerritories': 'Afghanistan', 'countryTerritoryId': 'AF', 'countryTerritoryCode': 'AFG', 'population2019': '38041757', 'continent': 'Asia', 'cumulativeper1000002Weeks': '1.3090878'}, {'date': '12/9/20', 'day': '12', 'month': '9', 'year': '2020', 'cases': '34', 'deaths': '0', 'countriesAndTerritories': 'Afghanistan', 'countryTerritoryId': 'AF', 'countryTerritoryCode': 'AFG', 'population2019': '38041757', 'continent': 'Asia', 'cumulativeper1000002Weeks': '1.22496971'}]

但是我想将“cases”和“population2019”中的值更改为整数而不是字符串。

我已使用此代码将字符串更改为整数

for i in dataset:        #Changes the value of multiple keys to integers instead of string 
    for key in i:
        i['cases'] = int(i['cases'])
        i['population2019'] = int(i['population2019'])

它确实将“cases”的值更改为整数而不是字符串,但它不适用于“population2019”,因为我认为它是一个大整数(“38041757”)。

错误是:

ValueError: invalid literal for int() with base 10: ''

标签: pythondictionaryinteger

解决方案


我相信你有这个错误,因为population2019当你尝试转换它时是一个空字符串 ('')


推荐阅读