简体   繁体   English

如何在python中更新字典中的值?

[英]How can I update a value in a dictionary in python?

I have a dictionary like this: 我有一个这样的字典:

my_dict = {key1:value1, key2:value2}

I want to first check if some key exists if yes I have to convert the value of existing key into a list and add other value to that like this: 我想首先检查一些密钥是否存在,如果是,我必须将现有密钥的值转换为列表并添加其他值,如下所示:

my_dict = {key1:[value1,new_value], key2:value2}

I mean just I need to update one key in the dictionary to list not all of them. 我的意思是我需要更新字典中的一个键以列出并非所有键。 any idea about that? 有什么想法吗?

This is a solution that works even if you add multiple values to a certain key. 即使您向某个键添加多个值,这个解决方案仍然有效。 You can have a separate function for this: 你可以有一个单独的功能:

#!/usr/bin/env python

def append_value(d, key, value):
    if not key in d:
        d[key] = value
    else:
        if type(d[key]) != list:
            d[key] = [d[key], value]
        else:
            d[key].append(value)



my_dict = {"key1": 1, "key2": 2}
print(my_dict)


append_value(my_dict, 'key1', 4)
print(my_dict)
append_value(my_dict, 'key1', 5)
print(my_dict)
append_value(my_dict, 'key3', 6) # adding a key that doesn't exist
print(my_dict)
append_value(my_dict, 'key3', 7)
print(my_dict)

The output would be: 输出将是:

{'key2': 2, 'key1': 1} # initial value
{'key2': 2, 'key1': [1, 4]} # adding 4 to key1
{'key2': 2, 'key1': [1, 4, 5]} # adding 5 to key1
{'key3': 6, 'key2': 2, 'key1': [1, 4, 5]} # adding new key: key3
{'key3': [6, 7], 'key2': 2, 'key1': [1, 4, 5]} # adding 7 to key3

If you may have one or more values for a given key, it's usually a better idea to always use a list for the value, rather than sometimes having a list and sometimes having the value directly. 如果您可能有一个或多个给定键的值,通常最好始终使用列表作为值,而不是有时使用列表,有时直接使用值。 The list can have just one item in it, or it can have more. 列表中只能包含一个项目,或者可以包含更多项目。 This way you can always use the same code to access and modify the values, regardless of how many of them there are. 这样,您始终可以使用相同的代码来访问和修改值,无论它们有多少。

There are several good ways to add values to such a dictionary. 有几种很好的方法可以为这样的字典添加值。 The setdefault method is an easy one that works with regular dictionaries: setdefault方法很简单,适用于常规字典:

d = {"key1": ["value1"], "key2": ["value2"]}  # values are always lists

d.setdefault("key1", []).append("new_value")      # this adds a value to an existing list
d.setdefault("new_key", []).append("new_value2")  # this time the same code creates a new list

You can also use a collections.defaultdict , which will create new values automatically whenever you look up a key that isn't in the dictionary yet. 您还可以使用collections.defaultdict ,当您查找尚未在字典中的键时,它将自动创建新值。

from collections import defaultdict

d = defaultdict(list)  # list is the "factory" that gets called to create new values

d["key1"].append("value1")
d["key2"].append("value2")
d["key1"].append("new_value")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM