![](/img/trans.png)
[英]how to construct a dictionary from two lists mapping that key to the value at the corresponding index in the list of values in python
[英]Python: How to construct a tuple, value dictionary from a list of key,value dictionary?
我有以下字典列表:
lst = [{'unitname':'unit1', 'test1': 2, 'test2': 9}, {'unitname':'unit2', 'test1': 24, 'test2': 35}]
我如何构造一个单一的字典,如下所示:
dictA = { ('unit1','test1'): 2, ('unit1','test2'): 9, ('unit2','test1'):24, ('unit2','test2' : 35 }
`
我在列表中有所有单元名称和测试名称:
unitnames = ['unit1','unit2']
testnames = ['test1','test2']
我尝试过,但是错过了某些单元的测试。
dictA = {}
for unit in unitnames:
for dict in lst:
for k,v in dict.items():
dictA[unit,k] = v
忠告? 谢谢。
您可以尝试:
dictA = {}
for l in lst:
name = l.pop('unitname')
for test in l:
dictA[name, test] = l[test]
与Gareth的解决方案同时发布并具有相同的假设-但这不会给您额外的(name,'unitname')= name项
Marcelo Cantos的解决方案非常优雅,但对于像我们这样的凡人来说,解析起来会更容易:
dict( ((d['unitname'], k), t)
for d in lst
for (k, t) in d.iteritems()
if k != 'unitname'
)
dict(((d['unitname'], k), t)
for d in lst
for (k, t) in d.iteritems()
if k != 'unitname')
dictA = {}
for d in lst:
unit = d['unitname']
for test in testnames:
if test in d:
dictA[unit,test] = d[test]
我假设(1)您列表中的所有字典都有一个unitname
键,(2)它的值始终是您感兴趣的单位之一,(3)列表中的某些字典可能具有用于您不感兴趣的测试,以及(4)列表中的某些命令可能没有您感兴趣的某些测试。 这些假设有些武断。 如果碰巧是错误的,则不难为它们调整代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.