如何向python中的字典键添加多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20585920/
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 20:47:32  来源:igfitidea点击:

How to add multiple values to a dictionary key in python?

pythondictionarykey

提问by PythonEnthusiast

I want to add multiple values to a specific key in a python dictionary. How can I do that?

我想向 python 字典中的特定键添加多个值。我怎样才能做到这一点?

a = {}
a["abc"] = 1
a["abc"] = 2

This will replace the value of a["abc"] from 1 to 2.

这会将 a["abc"] 的值从 1 替换为 2。

What I want instead is for a["abc"] to have multiple values(both 1 and 2).

我想要的是 a["abc"] 具有多个值(1 和 2)。

回答by MattDMo

How about

怎么样

a["abc"] = [1, 2]

This will result in:

这将导致:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

这就是你要找的吗?

回答by President James K. Polk

Make the value a list, e.g.

将值设为列表,例如

a["abc"] = [1, 2, "bob"]

UPDATE:

更新:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

有几种方法可以向键添加值,并在没有列表的情况下创建一个列表。我将逐步展示一种这样的方法。

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

结果:

>>> a
{'somekey': [1]}

Next, try:

接下来,尝试:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

结果:

>>> a
{'somekey': [1, 2]}

The magic of setdefaultis that it initializes the value for that key ifthat key is not defined, otherwise it does nothing. Now, noting that setdefaultreturns the key you can combine these into a single line:

的神奇之处setdefault在于,如果该键未定义,它会初始化该键的值,否则它什么都不做。现在,注意setdefault返回键,您可以将它们组合成一行:

a.setdefault("somekey",[]).append("bob")

Results:

结果:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dictmethods, in particular the get()method, and do some experiments to get comfortable with this.

你应该看看dict方法,特别是get()方法,并做一些实验来适应这一点。