如何在python字典中为每个键添加多个值

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

How to add multiple values per key in python dictionary

pythondictionarykey

提问by jsnabs2

My program needs to output a list of names with three numbers corresponding to each name however I don't know how to code this is there a way I could do it as a dictionary such as cat1 = {"james":6, "bob":3}but with three values for each key?

我的程序需要输出一个名称列表,其中包含与每个名称对应的三个数字,但是我不知道如何编码,有没有一种方法可以将其作为字典来实现,例如cat1 = {"james":6, "bob":3}每个键具有三个值?

采纳答案by Alex

The value for each key can either be a set (distinct list of unordered elements)

每个键的值可以是一个集合(无序元素的不同列表)

cat1 = {"james":{1,2,3}, "bob":{3,4,5}}
for x in cat1['james']:
    print x

or a list (ordered sequence of elements )

或列表(元素的有序序列)

cat1 = {"james":[1,2,3], "bob":[3,4,5]}
for x in cat1['james']:
    print x

回答by Dr Xorile

Both answers are fine. @santosh.ankr used a dictionary of lists. @Jaco de Groot used a dictionary of sets (which means you cannot have repeated elements).

两个答案都很好。@santosh.ankr 使用了一个列表字典。@Jaco de Groot 使用了一个集合字典(这意味着你不能有重复的元素)。

Something that is sometimes useful if you're using a dictionary of lists (or other things) is a default dictionary.

如果您使用列表(或其他东西)的字典,有时会有用的东西是默认字典

With this you can append to items in your dictionary even if they haven't been instantiated:

有了这个,即使它们尚未实例化,您也可以附加到字典中的项目:

>>> from collections import defaultdict
>>> cat1 = defaultdict(list)
>>> cat1['james'].append(3)   #would not normally work
>>> cat1['james'].append(2)
>>> cat1['bob'].append(3)     #would not normally work
>>> cat1['bob'].append(4)
>>> cat1['bob'].append(5)
>>> cat1['james'].append(5)
>>> cat1
defaultdict(<type 'list'>, {'james': [3, 2, 5], 'bob': [3, 4, 5]})
>>> 

回答by Ahmed tiger

the key name and values to every key:

每个键的键名和值:

student = {'name' : {"Ahmed " , "Ali " , "Moahmed "} , 'age' : {10 , 20 , 50} }

for keysName in student:
    print(keysName)
    if keysName == 'name' :
        for value in student[str(keysName)]:
            print("Hi , " + str(value))
    else:
        for value in student[str(keysName)]:
            print("the age :  " + str(value))

And the output :

和输出:

name
Hi , Ahmed 
Hi , Ali 
Hi , Moahmed 
age
the age :  50
the age :  10
the age :  20