带有键值对作为键值的Python字典

时间:2019-09-25 09:43:59

标签: python dictionary python-3.6

我想知道如何创建具有键值对的字典,并且值应该具有另一个值。

例如:

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

我尝试过

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

然后a返回

{ key: {value : c } }

对于价值,最后添加的只是获得。

1 个答案:

答案 0 :(得分: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看起来像{'key':{'value':[a,b,c]}}

 #To read data iterate over nested dict
for k,v in a.iteritems():
print k
print v['value']
相关问题