当前位置: 代码迷 >> python >> 如何正确更改密钥名称?
  详细解决方案

如何正确更改密钥名称?

热度:71   发布时间:2023-07-16 10:43:17.0

我想更改字典中的键名,我使用的代码如下:

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],

您在迭代时弹出/添加字典中的键/向字典添加键。 不要那样做 例如,您可以遍历提取的键列表:

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)

您的代码有两个问题:

for key in my_dict_other:
    new_key = key + '/' + str(my_dict[key])
    my_dict_other[new_key] = my_dict_other.pop(key)
  1. 您正在更改要遍历的对象。这是不行的 添加元素也使循环永无止境!
  2. 您正在遍历my_dict_other的键, my_dict_other每个my_dict[key]进行my_dict[key]的操作。 您确定my_dict包含它们全部吗? 如果不是,则执行my_dict.get(key, '')或在其中添加if检查。
  3. 它们中最大的失败,最终导致代码中断的是1.2.的组合。 您正在将重点'31-0/[5400, 3601]'在第一次迭代,并在某些时候它成为你的key (如for key in my_dict_other键),它当然不会在存在my_dict因而KeyError

[为了完整起见]除了schwobaseggl的答案,您还可以将新的键值写入具有新名称的新字典中:

fresh = {}
for key in my_dict_other: 
    fresh[(key + '/' + str(my_dict[key]))] = my_dict_other(key)

但是正如Ev.Kounis提到的那样,您需要确保my_dict词典包含相同的键...从.pop调用中获取KeyError的原因可能是由于该键不在您的主机中my_dict。

  相关解决方案