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


当前回答

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

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

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

没有理由不能添加紫色->2或删除红色->1并添加橙色->1

其他回答

我只是要帮我妻子做一些python类的事情,所以我写了这段代码来告诉她如何做。正如标题所示,它只替换键名。这是非常罕见的,你必须替换一个键名,并保持字典的顺序完整,但我还是想分享,因为这篇文章是当你搜索它时谷歌返回的,即使它是一个非常老的线程。

代码:

dictionary = {
    "cat": "meow",
    "dog": "woof",
    "cow": "ding ding ding",
    "goat": "beh"
}


def countKeys(dictionary):
    num = 0
    for key, value in dictionary.items():
        num += 1
    return num


def keyPosition(dictionary, search):
    num = 0
    for key, value in dictionary.items():
        if key == search:
            return num
        num += 1


def replaceKey(dictionary, position, newKey):
    num = 0
    updatedDictionary = {}
    for key, value in dictionary.items():
        if num == position:
            updatedDictionary.update({newKey: value})
        else:
            updatedDictionary.update({key: value})
        num += 1
    return updatedDictionary


for x in dictionary:
    print("A", x, "goes", dictionary[x])
    numKeys = countKeys(dictionary)

print("There are", numKeys, "animals in this list.\n")
print("Woops, that's not what a cow says...")

keyPos = keyPosition(dictionary, "cow")
print("Cow is in the", keyPos, "position, lets put a fox there instead...\n")
dictionary = replaceKey(dictionary, keyPos, "fox")

for x in dictionary:
    print("A", x, "goes", dictionary[x])

输出:

A cat goes meow
A dog goes woof
A cow goes ding ding ding
A goat goes beh
There are 4 animals in this list.

Woops, that's not what a cow says...
Cow is in the 2 position, lets put a fox there instead...

A cat goes meow
A dog goes woof
A fox goes ding ding ding
A goat goes beh

用下划线替换字典键中的空格,我使用这个简单的路由…

for k in dictionary.copy():
    if ' ' in k:
        dictionary[ k.replace(' ', '_') ] = dictionary.pop(k, 'e r r')

或者只是dictionary。pop(k)注意'e r r',它可以是任何字符串,如果键不在字典中,就会成为新的值,从而能够替换它,这在这里不可能发生。参数是可选的,在其他类似的代码中,KeyError可能会被击中,添加的arg会避免它,但可以创建一个新的键'e rr '或任何你设置的值。

.copy()避免…字典在迭代过程中改变了大小。

.keys()不需要,k是每个键,k在我的头脑中代表键。

(我使用v3.7)

关于字典pop()的信息

上面循环的一行代码是什么?

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

如果你有一个复杂的字典,这意味着字典中有一个字典或列表:

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

这个函数获得一个字典,另一个字典指定如何重命名键;它返回一个新的字典,带有重命名的键:

def rekey(inp_dict, keys_replace):
    return {keys_replace.get(k, k): v for k, v in inp_dict.items()}

测试:

def test_rekey():
    assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}