complicated list and dictionary lookup in python -


i have list of tuples , dictionary of lists 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 want look-up item in list within dol exists in of tuples given in lot. if requirement met, want add variable respective tuple.

currently doing follows (which looks incredibly inefficient , ugly). want know efficient , neat way of achieving this. possibilities ?

ps: looking preserve order of lot while doing this.

merged = [x[0] x in lot]  x in dol:     item in dol[x]:         if item in merged:             x in lot:                 if x[0] == item:                     lot[lot.index(x)] += (true, ) 

first, build set of values inside of dol structure:

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

now membership testing efficient, , can use list comprehension:

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

demo:

>>> 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 tup in lot] [('item 1', 43, true), ('item 4', 82, true), ('item 12', 33), ('item 10', 21)] 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -