-2

I want to know how to create a dictionary with key value pair and value should have another values.

For example:

{key:{value1 : [a,b,c] , value2 : [d,e,f] , value3 : [g,h,i] } }

I tried,

a = {}
a.setdefault(key,{})[value] = a
a.setdefault(key,{})[value] = b
a.setdefault(key,{})[value] = c

then a returns

{ key: {value : c } }

For value last one added is only getting.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Student
  • 41
  • 2
  • 10
  • Possible duplicate of [How to add multiple values to a dictionary key in python?](https://stackoverflow.com/questions/20585920/how-to-add-multiple-values-to-a-dictionary-key-in-python) – jonrsharpe Sep 25 '19 at 09:47
  • does ```key``` var change it's value? – dorintufar Sep 25 '19 at 09:48

1 Answers1

0
from collections import defaultdict
#create nested dict using defaultdict
a = defaultdict(lambda:defaultdict(list))
#above line will create dict of dict where internal dict holds list of values
a['key']['value'].append('a')
a['key']['value'].append('b')
a['key']['value'].append('c')

a looks like {'key':{'value':[a,b,c]}}

 #To read data iterate over nested dict
for k,v in a.iteritems():
print k
print v['value']
Rangoli Thakur
  • 335
  • 3
  • 4