Div*_*dev 2 python dictionary casting list typeerror
我有一本字典
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 integer
Run Code Online (Sandbox Code Playgroud)
因此,如果有人可以帮助我找到解决方案,请这样做......
假设值中的所有元素都是数字,您可以map int对值:
maketh_new = {k: list(map(int, v)) for k, v in maketh.items()}
Run Code Online (Sandbox Code Playgroud)
输出:
{'n': [1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
Run Code Online (Sandbox Code Playgroud)
如果没有,您可以使用str.isdigit更安全的输入:
maketh = {'n':['1', '2', 'a'], # Note 'a' at last
'g': ['0', '5', '6', '9'],
'ca': ['4', '8', '1', '5', '9', '0']}
maketh_new = {k: [int(i) if i.isdigit() else i for i in v] for k, v in maketh.items()}
Run Code Online (Sandbox Code Playgroud)
输出:
{'n': [1, 2, 'a'], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
Run Code Online (Sandbox Code Playgroud)