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


当前回答

完整解决方案的示例

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

其他回答

只需2步即可轻松完成:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

或者一步:

dictionary[new_key] = dictionary.pop(old_key)

如果字典[old_key]未定义,将引发KeyError。注意,这将删除字典[old_key]。

>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 1

如果你想更改所有的键:

d = {'x':1, 'y':2, 'z':3}
d1 = {'x':'a', 'y':'b', 'z':'c'}

In [10]: dict((d1[key], value) for (key, value) in d.items())
Out[10]: {'a': 1, 'b': 2, 'c': 3}

如果你想改变单键: 你可以选择上面的任何一个建议。

d = {1:2,3:4}

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

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

我们得到

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

在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()}

这将小写你所有的字典键。即使你有嵌套的字典或列表。您可以执行类似的操作来应用其他转换。

def lowercase_keys(obj):
  if isinstance(obj, dict):
    obj = {key.lower(): value for key, value in obj.items()}
    for key, value in obj.items():         
      if isinstance(value, list):
        for idx, item in enumerate(value):
          value[idx] = lowercase_keys(item)
      obj[key] = lowercase_keys(value)
  return obj 
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}

lowercase_keys(json_str)


Out[0]: {'foo': 'BAR',
 'bar': 123,
 'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
 'emb_dict': {'foo': 'BAR',
  'bar': 123,
  'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}