I have a dictionary of a list of tuples:
adict = {'alpha': [('0', 'beta'), ('1', 'beta')],
'beta': [('0', 'alpha'), ('1', 'alpha')]}
and a list of values:
alist = ['alpha', '0', '1', '0']
blist = ['beta', '0', '1', '0', 'x']
I want to be able to use the first index as a key to search through the dictionary and then using the numbers in the list to search through the tuples and append matched tuples (with the first element of the tuple) with the value into a final list. I don't know if I'm being clear enough but in the end I want the final list to be
final_list = [ ['alpha', ('0', 'beta'), ('1', 'beta'), ('0', 'beta')],
['beta', ('0', 'alpha'), ('1', 'alpha'), ('0', 'alpha'), ('x': None)] ]
Its sort of a multi-level search. How would I approach this?
Create a temporary dict first, in which the values of adict
are dictionary itself. And then use a list comprehension to get the desired list.
>>> temp_adict = {k:dict(v) for k, v in adict.items()}
>>> [ lis[:1] + [(x, temp_adict[lis[0]].get(x)) for x in lis[1:]]
for lis in [alist, blist]]
[['alpha', ('0', 'beta'), ('1', 'beta'), ('0', 'beta')],
['beta', ('0', 'alpha'), ('1', 'alpha'), ('0', 'alpha'), ('x', None)]]
this ugliness does the thing in one line.... beware, it's ugly!
solution = [[alist[0]] + [(key, adict[alist[0]][index][1]) for key in alist[1:] for index in xrange(len(adict[alist[0]])) if adict[alist[0]][index][0] == key]] + [[blist[0]] + [(key, adict[blist[0]][index][1]) for key in blist[1:] for index in xrange(len(adict[alist[0]])) if adict[alist[0]][index][0] == key]]
it's also not very DRY, just does the job in 1 line, if that matters for whatever reason
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.