【问题标题】:Python dictionary with key value pair as value for a key以键值对作为键值的 Python 字典
【发布时间】:2019-09-25 09:43:59
【问题描述】:

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

例如:

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

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

【问题讨论】:

标签: python dictionary python-3.6


【解决方案1】:
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']

【讨论】:

  • 请添加说明,因为您的帖子属于“低质量帖子”类别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2021-01-19
  • 2011-09-05
相关资源
最近更新 更多