[英]How to dump/append all the values of a dict into a list if key is a tuple?
我有一个字典,列表中有单元名称和测试名称,如下所示:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']
testnames = ['test1','test2']
我们如何将test1的所有值附加到列表中? 即
temp = [10,78] # test1 values
temp2 = [2,45] # test2 values
看来您是在询问清单推论 。
[v for k,v in dictA.iteritems() if k[1] == 'test1']
会给你:
[10, 78]
同理:
>>> [v for k,v in dictA.iteritems() if k[1] == 'test2']
[2, 45]
现在,这里的key
是一个元组,我们在引用的元素if
-clause。
temp = [ j for i, j in dictA.iteritems() if "test1" in i ]
我会把dictA变成a,因为那是字典的字典-通过转换或通过以这种形式构造它来更好
dictA = {'unit1':{'test1': 10, 'test2': 2}, 'unit2': {'test1': 78, 'test2': 45}}
然后
temp = [dictA[x]['test1'] for x in units]
temp2 = [dictA[x]['test2'] for x in units]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.