小编Div*_*dev的帖子

如果字典中的值位于列表中,如何将它们从字符串更改为整数

我有一本字典

maketh = {'n':['1', '2', '3'], 'g': ['0', '5', '6', '9'], 'ca': ['4', '8', '1', '5', '9', '0']}

我打算改为

maketh_new = {'n':[1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}

数字在值中的顺序非常重要。因此,即使更改后顺序也应保持不变。

当我尝试使用任何在线可用的方法更改它时,我总是遇到的错误是:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

“如有打字错误,请忽略……”

我自己写的一篇文章认为这样的事情可能可行:

maketh_new = dict()

for (key, values) in maketh.items():
    for find in len(values):
        maketh_new [key] = int(values[find])   
Run Code Online (Sandbox Code Playgroud)

我尝试了一下,认为如果我可以以字符串形式访问列表中值的所有元素,那么我也许可以将其类型转换为 int。但我得到一个错误:

'list' object cannot be interpreted as an …
Run Code Online (Sandbox Code Playgroud)

python dictionary casting list typeerror

2
推荐指数
1
解决办法
149
查看次数

标签 统计

casting ×1

dictionary ×1

list ×1

python ×1

typeerror ×1