标签归档:sequence

更改字典中键的名称

问题:更改字典中键的名称

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

有没有简单的方法可以做到这一点?

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

Is there a straightforward way to do this?


回答 0

只需2个步骤即可轻松完成:

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

或第一步

dictionary[new_key] = dictionary.pop(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

Easily done in 2 steps:

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

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key)

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete 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

回答 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}

如果要更改单个键:可以采用上述任何建议。

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.


回答 2

流行的

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

pop’n’fresh

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

回答 3

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

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 ‘:’

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


回答 4

由于键是字典用于查找值的对象,因此您无法真正更改它们。您可以做的最接近的操作是保存与旧密钥关联的值,将其删除,然后添加带有替换密钥和已保存值的新条目。其他几个答案说明了可以完成此操作的不同方式。

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.


回答 5

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

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'}}

If you have a complex dict, it means there is a dict or list within the 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'}}

回答 6

没有直接的方法可以执行此操作,但是您可以删除然后分配

d = {1:2,3:4}

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

或进行批量密钥更改:

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

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

回答 7

转换字典中的所有键

假设这是您的字典:

>>> sample = {'person-id': '3', 'person-name': 'Bob'}

要将所有破折号转换为示例字典键中的下划线:

>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}

To convert all the keys in the dictionary

Suppose this is your dictionary:

>>> sample = {'person-id': '3', 'person-name': 'Bob'}

To convert all the dashes to underscores in the sample dictionary key:

>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}

回答 8

d = {1:2,3:4}

假设我们想将键更改为列表元素p = [‘a’,’b’]。以下代码将执行以下操作:

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

我们得到

{'a': 2, 'b': 4}
d = {1:2,3:4}

suppose that we want to change the keys to the list elements p=[‘a’ , ‘b’]. the following code will do:

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

and we get

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

回答 9

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

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

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

没有理由您无法添加purple->2或删除red->1并添加orange->1

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->2 or remove red->1 and add orange->1


回答 10

如果一次更改所有按键。在这里,我将阻止所有键。

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

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

回答 11

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

dict['key'] = value

您甚至可以对对象属性执行此操作。通过执行以下操作使它们成为字典:

dict = vars(obj)

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

dict['attribute'] = value

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