简体   繁体   English

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

[英]How to add multiple values per key in python dictionary

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

Both answers are fine.两个答案都很好。 @santosh.ankr used a dictionary of lists. @santosh.ankr 使用了一个列表字典。 @Jaco de Groot used a dictionary of sets (which means you cannot have repeated elements). @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]})
>>> 

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

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

Add multiple values in same dictionary key :在同一个字典键中添加多个值:

subject = 'Computer'
numbers = [67.0,22.0]

book_dict = {}
book_dict.setdefault(subject, [])

for number in numbers
   book_dict[subject].append(number)

Result:结果:

{'Computer': [67.0, 22.0]}

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

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