Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
jsnabs2 Avatar asked Jan 08 '23 16:01

jsnabs2


2 Answers

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

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]})
>>> 
like image 51
Dr Xorile Avatar answered Jan 17 '23 13:01

Dr Xorile


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
like image 25
Alex Avatar answered Jan 17 '23 14:01

Alex