简体   繁体   English

如何获取和使用元组列表的dict中的值

[英]How to get and use values from a dict of a list of tuples

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. 首先创建一个临时字典,其中adict的值是字典本身。 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 它也不是很干,只要在一行中完成工作,如果这无关紧要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM