且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 20:19:40

将值设为列表,例如

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

更新:

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

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

结果:

>>>一个{'somekey':[1]}

接下来,尝试:

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

结果:

>>>一个{'somekey': [1, 2]}

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

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

结果:

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

您应该查看 dict 方法,尤其是 get() 方法,并进行一些实验以适应这一点.

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

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

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

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

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 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")

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.