简体   繁体   English

如何将多个值添加到字典键?

[英]How to add multiple values to a dictionary key?

I want to add multiple values to a specific key in a python dictionary.我想将多个值添加到 python 字典中的特定键。 How can I do that?我怎样才能做到这一点?

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"]有多个值( 12 )。

Make the value a list, eg使值成为一个列表,例如

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 setdefault is that it initializes the value for that key if that key is not defined. setdefault的神奇之处在于,如果未定义该键,它会初始化该键的值。 Now, noting that setdefault returns the value, you can combine these into a single line:现在,请注意setdefault返回值,您可以将它们组合成一行:

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

Results:结果:

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

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.您应该查看dict方法,特别是get()方法,并进行一些实验以适应它。

How about怎么样

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

This will result in:这将导致:

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

Is that what you were looking for?那是你要找的吗?

  • Append list elements追加列表元素

If the dict values need to be extended by another list, extend() method of list s may be useful.如果 dict 值需要由另一个列表扩展, listextend()方法可能很有用。

a = {}
a.setdefault('abc', []).append(1)       # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3])  # a is now {'abc': [1, 2, 3]}

This can be especially useful in a loop where values need to be appended or extended depending on datatype.这在需要根据数据类型附加或扩展值的循环中特别有用。

a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
    if isinstance(v, list):
        a.setdefault(some_key, []).extend(v)
    else:
        a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
  • Append list elements without duplicates追加不重复的列表元素

If there's a dictionary such as a = {'abc': [1, 2, 3]} and it needs to be extended by [2, 4] without duplicates, checking for duplicates (via in operator) should do the trick.如果存在诸如a = {'abc': [1, 2, 3]}之类的字典,并且需要将其扩展为[2, 4]而没有重复,则检查重复(通过in运算符)应该可以解决问题。 The magic of get() method is that a default value can be set (in this case empty set ( [] )) in case a key doesn't exist in a , so that the membership test doesn't error out. get()方法的神奇之处在于可以设置默认值(在本例中为空集( [] )),以防a中不存在键,以便成员资格测试不会出错。

a = {some_key: [1, 2, 3]}

for v in [2, 4]:
    if v not in a.get(some_key, []):
        a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}

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

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