Python 更改字典中键的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4406501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:35:57  来源:igfitidea点击:

Change the name of a key in dictionary

pythondictionarysequence

提问by user469652

I want to change the key of an entry in a Python dictionary.

我想更改 Python 字典中条目的键。

Is there a straightforward way to do this?

有没有直接的方法来做到这一点?

采纳答案by moinudin

Easily done in 2 steps:

只需两步即可轻松完成:

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

Or in 1 step:

或分 1 步:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyErrorif dictionary[old_key]is undefined. Note that this willdelete dictionary[old_key].

KeyError如果dictionary[old_key]未定义,它将引发。请注意,这删除dictionary[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

回答by DGH

You can associate the same value with many keys, or just remove a key and re-add a new key with the same value.

您可以将相同的值与多个键相关联,或者只是删除一个键并重新添加具有相同值的新键。

For example, if you have keys->values:

例如,如果您有键->值:

red->1
blue->2
green->4

there's no reason you can't add purple->2or remove red->1and add orange->1

没有理由不能添加purple->2或删除red->1和添加orange->1

回答by AndiDog

No direct way to do this, but you can delete-then-assign

没有直接的方法可以做到这一点,但您可以先删除再分配

d = {1:2,3:4}

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

or do mass key changes:

或进行批量密钥更改:

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

回答by kevpie

pop'n'fresh

pop'n'fresh

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

回答by Tauquir

if you want to change all the keys:

如果要更改所有键:

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}

if you want to change single key: You can go with any of the above suggestion.

如果您想更改单个密钥:您可以采用上述任何建议。

回答by martineau

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.

由于键是字典用来查找值的东西,因此您无法真正更改它们。您可以做的最接近的事情是保存与旧键关联的值,将其删除,然后使用替换键和保存的值添加新条目。其他几个答案说明了实现这一目标的不同方式。

回答by MicahT

I haven't seen this exact answer:

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

dict['key'] = value

You can even do this to object attributes. Make them into a dictionary by doing this:

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

dict = vars(obj)

Then you can manipulate the object attributes like you would a dictionary:

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

dict['attribute'] = value

回答by Ward

In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'

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

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}

to get rid of the trailing ':' in the keys:

摆脱键中的尾随“:”:

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

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

回答by Hatem

If you have a complex dict, it means there is a dict or list within the dict:

如果您有一个复杂的 dict,则表示该 dict 中有一个 dict 或列表:

myDict = {1:"one",2:{3:"three",4:"four"}}
myDict[2][5] = myDict[2].pop(4)
print myDict

Output
{1: 'one', 2: {3: 'three', 5: 'four'}}

回答by Ananth Kumar Vasamsetti

In case of changing all the keys at once. Here I am stemming the keys.

在一次更改所有键的情况下。在这里,我正在阻止密钥。

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