Skip to content
Advertisement

How to add multiple values per key in python dictionary

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement