Sophisticated list and dictionary lookup in python

I have a list of tuples and a dictionary of lists as follows.

 # List of tuples lot = [('Item 1', 43), ('Item 4', 82), ('Item 12', 33), ('Item 10', 21)] # dict of lists dol = { 'item_category_one': ['Item 3', 'Item 4'], 'item_category_two': ['Item 1'], 'item_category_thr': ['Item 2', 'Item 21'], } 

Now I want to see where any element in any list inside dol exists in any of the tuples specified in lot . If this requirement is met, then I want to add another variable to the corresponding tuple.

Currently, I am doing it as follows (which looks incredibly inefficient and ugly). I would like to know the most effective effective and neat way to achieve this. what are the possibilities?

PS: I also try to keep the lot order at the same time.

 merged = [x[0] for x in lot] for x in dol: for item in dol[x]: if item in merged: for x in lot: if x[0] == item: lot[lot.index(x)] += (True, ) 
+4
source share
1 answer

First create a set of all your values ​​inside the dol structure:

 from itertools import chain dol_values = set(chain.from_iterable(dol.itervalues())) 

Membership testing is now effective and you can use list comprehension:

 [tup + (True,) if tup[0] in dol_values else tup for tup in lot] 

Demo:

 >>> from itertools import chain >>> dol_values = set(chain.from_iterable(dol.itervalues())) >>> dol_values set(['Item 3', 'Item 2', 'Item 1', 'Item 21', 'Item 4']) >>> [tup + (True,) if tup[0] in dol_values else tup for tup in lot] [('Item 1', 43, True), ('Item 4', 82, True), ('Item 12', 33), ('Item 10', 21)] 
+5
source

Source: https://habr.com/ru/post/1480923/


All Articles