如何更改Python字典中条目的键?


当前回答

我还没有看到确切的答案:

dict['key'] = value

您甚至可以对对象属性执行此操作。 通过这样做,将它们编入字典:

dict = vars(obj)

然后你可以像操作字典一样操作对象属性:

dict['attribute'] = value

其他回答

注意pop的位置: 将你想要删除的键放在pop()之后 orig_dict['AAAAA'] = orig_dict.pop('A')

orig_dict = {'A': 1, 'B' : 5,  'C' : 10, 'D' : 15}   
# printing initial 
print ("original: ", orig_dict) 

# changing keys of dictionary 
orig_dict['AAAAA'] = orig_dict.pop('A')
  
# printing final result 
print ("Changed: ", str(orig_dict)) 

我还没有看到确切的答案:

dict['key'] = value

您甚至可以对对象属性执行此操作。 通过这样做,将它们编入字典:

dict = vars(obj)

然后你可以像操作字典一样操作对象属性:

dict['attribute'] = value

以防一次换了所有的钥匙。 我在这里阻塞钥匙。

a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output

完整解决方案的示例

声明一个json文件,其中包含你想要的映射

{
  "old_key_name": "new_key_name",
  "old_key_name_2": "new_key_name_2",
}

加载它

with open("<filepath>") as json_file:
    format_dict = json.load(json_file)

创建此函数来使用映射格式化字典

def format_output(dict_to_format,format_dict):
  for row in dict_to_format:
    if row in format_dict.keys() and row != format_dict[row]:
      dict_to_format[format_dict[row]] = dict_to_format.pop(row)
  return dict_to_format
d = {1:2,3:4}

假设我们想要改变列表元素p=['a', 'b']的键值。 下面的代码可以做到:

d=dict(zip(p,list(d.values()))) 

我们得到

{'a': 2, 'b': 4}