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


当前回答

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

其他回答

流行与新鲜

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

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

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

我们得到

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

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

dict['key'] = value

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

dict = vars(obj)

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

dict['attribute'] = value

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

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

我只是要帮我妻子做一些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