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


当前回答

d = {1:2,3:4}

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

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

我们得到

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

其他回答

流行与新鲜

>>>a = {1:2, 3:4}
>>>a[5] = a.pop(1)
>>>a
{3: 4, 5: 2}
>>> 

完整解决方案的示例

声明一个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

在python 2.7及更高版本中,您可以使用字典理解: 这是我在使用DictReader读取CSV时遇到的一个例子。用户已经在所有列名后面加上了':'

ori_dict ={“key1:”:1、“key2:”:2,“key3:”:3}

在键中去掉后面的':':

Corrected_dict = {k.replace(':', "): v for k, v in ori_dict.items()}

没有直接的方法做到这一点,但你可以删除然后分配

d = {1:2,3:4}

d[newKey] = d[1]
del d[1]

或者做大量的键改变:

d = dict((changeKey(k), v) for k, v in d.items())

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

dict['key'] = value

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

dict = vars(obj)

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

dict['attribute'] = value