数据变量包含整数作为键,另一个字典作为值。但是,引号中的0被认为是字符串。我想将其转换为整数。
data[keys].keys()
dict_keys(['0', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
答案 0 :(得分:2)
修复字典的简单方法是
d[0] = d['0']
del d['0']
但是,这是一个方便的函数,可用于将所有char int键转换为int:
def convert_dict(d):
keys = list(d.keys())
for key in keys:
if isinstance(key, str):
try:
int_key = int(key)
d[int_key] = d[key]
del d[key]
except ValueError:
pass
return d
测试
d = {'0':0, 1:1, 2:2, 'hello': 'world'}
convert_dict(d)
{1: 1, 2: 2, 'hello': 'world', 0: 0}