4

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
jsnabs2
  • 113
  • 2
  • 2
  • 5

4 Answers4

5

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]})
>>> 
Dr Xorile
  • 967
  • 1
  • 7
  • 20
3

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
Alex
  • 21,273
  • 10
  • 61
  • 73
  • 2
    The value of the keys in `cat1` are `set`s. Just something to point out. – Zizouz212 Mar 25 '15 at 22:51
  • 1
    I almost always explicitly declare sets using the set() call to avoid confusion with dictionaries. You really shouldn't have to examine the thing for colons before you know what it is. – santosh.ankr Mar 25 '15 at 23:25
  • you could also use a dictionary containing a tuple with keys: cat1 = { "james": (1, 2, 3), "bob": (3, 4, 5) } – William Stuart Jan 18 '21 at 00:54
1

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
Ahmed tiger
  • 528
  • 1
  • 5
  • 10
0

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]}