如何在python中的字典键中添加多个值? [英] How to add multiple values to a dictionary key in python?
问题描述
我想为特定的键添加多个值。如何做到这一点?
I want to add multiple values to a specific key. How can I do that?
a = {}
a["abc"] = 1
a["abc"] = 2
推荐答案
,例如
a["abc"] = [1, 2, "bob"]
更新:
有几种方法可以添加值到键,并创建一个列表,如果还没有。我会在几个步骤中显示一个这样的方法。
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)
结果:
>>> a
{'somekey': [1]}
接下来,尝试:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
结果:
>>> a
{'somekey': [1, 2]}
setdefault
是它初始化该密钥的值,如果该键没有定义,否则它什么都不做。现在,注意到 setdefault
返回的键可以将它们组合成一行:
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
结果:
>>> a
{'somekey': [1, 2, 'bob']}
你应该看看 dict
方法,特别是 get()
方法,并做一些实验来使这个。
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
这篇关于如何在python中的字典键中添加多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!