我想更改字典中的密钥名,我使用的代码如下:
for key in my_dict_other:
print(key)
new_key = key + '/' + str(my_dict[key])
print(new_key)
my_dict_other[new_key] = my_dict_other.pop(key)我遇到的问题是,在第一次成功的代码迭代之后,会出现一个关键错误
输出:
38-7
38-7/[2550, 1651]
13-9
13-9/[2550, 1651]
16-15
16-15/[5100, 3301]
31-0/[5400, 3601]
Traceback (most recent call last):
new_key = key + '/' + str(my_dict[key])
KeyError: '31-0/[5400, 3601]'每次在不同的键上获取错误,所以似乎无法理解问题的模式或我的代码有什么问题
编辑:my_dict_other的结构:
'41-3': [['2436', '2459', '1901', '2152'],
['2704', '2253', '2442', '2062'],
['2763', '2595', '2498', '2518'],
['2190', '1918', '1970', '1875'],
['3154', '2442', '3023', '2417'],
['3360', '2481', '3252', '2458'],
['653', '1916', '430', '1874'],my_dict结构
'1-0': [5400, 3601],
'1-1': [2550, 1651],
'1-3': [5400, 3601],
'1-4': [5400, 3601],
'1-5': [5400, 3601],发布于 2018-02-12 08:58:08
在迭代时,您将弹出键并将键添加到dict中。别干那事。例如,您可以对您提取的密钥列表进行循环:
for key in list(my_dict_other): # loop over key list, not dict itself
new_key = key + '/' + str(my_dict[key]) # assuming key in my_dict!
my_dict_other[new_key] = my_dict_other.pop(key)发布于 2018-02-12 09:00:51
在这里,您的代码有两个问题:
for key in my_dict_other:
new_key = key + '/' + str(my_dict[key])
my_dict_other[new_key] = my_dict_other.pop(key)my_dict_other的键,并为每个键执行my_dict[key]。您确定my_dict包含所有这些内容吗?如果没有,那么在其中执行my_dict.get(key, '')或添加一个if检查。'31-0/[5400, 3601]',在某个时候它会变成您的key (就像在for key in my_dict_other键中一样),这当然不存在于my_dict中,因此也就是KeyError中。发布于 2018-02-12 09:11:16
为了完整,除了schwobaseggl的答案之外,您还可以将新的键值写入一个新的字典中,其中包含新的名称:
fresh = {}
for key in my_dict_other:
fresh[(key + '/' + str(my_dict[key]))] = my_dict_other(key)但是正如Ev.Kounis所提到的,您需要确保my_dict字典包含的keys...The原因与从.pop调用中获得KeyError的原因相同,这可能是因为密钥不在您的my_dict中。
https://stackoverflow.com/questions/48742487
复制相似问题