I have a dict as follows with unit names and testnames in a list:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']
testnames = ['test1','test2']
How do we append all values of say test1 into a list? ie
temp = [10,78] # test1 values
temp2 = [2,45] # test2 values
It looks like you're asking about list comprehensions .
[v for k,v in dictA.iteritems() if k[1] == 'test1']
Will give you:
[10, 78]
Similarly:
>>> [v for k,v in dictA.iteritems() if k[1] == 'test2']
[2, 45]
Now, where the key
is a tuple, we referenced the element in the if
-clause.
temp = [ j for i, j in dictA.iteritems() if "test1" in i ]
I would get dictA into a for that is dictionaries of dictionaries - either by conversion or better by constructing it in this form
dictA = {'unit1':{'test1': 10, 'test2': 2}, 'unit2': {'test1': 78, 'test2': 45}}
Then
temp = [dictA[x]['test1'] for x in units]
temp2 = [dictA[x]['test2'] for x in units]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.