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

时间:2021-01-09 18:10:12

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

我想为特定键添加多个值。我怎样才能做到这一点?

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

2 个解决方案

#1


85  

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添加值,如果还没有列表,则创建一个列表。我会在几步之内展示一种这样的方法。

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, otherwise it does nothing. Now, noting that setdefault returns 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 dict methods, in particular the get() method, and do some experiments to get comfortable with this.

你应该看一下dict方法,特别是get()方法,并做一些实验来熟悉它。

#2


13  

How about

怎么样

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

This will result in:

这将导致:

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

Is that what you were looking for?

那是你在找什么?

#1


85  

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添加值,如果还没有列表,则创建一个列表。我会在几步之内展示一种这样的方法。

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, otherwise it does nothing. Now, noting that setdefault returns 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 dict methods, in particular the get() method, and do some experiments to get comfortable with this.

你应该看一下dict方法,特别是get()方法,并做一些实验来熟悉它。

#2


13  

How about

怎么样

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

This will result in:

这将导致:

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

Is that what you were looking for?

那是你在找什么?