Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple key value lookup for dictionary in python

Tags:

python

So a lot of times I use dictionary for a key/value lookup. But if I need to lookup multiple things, I usually have a for loop for a same. For example:

def check_cond(key):
    return True if key in some_dict else False

some_task = [val for val in vals if check_cond(val)]

Is there a better way to search for all vals in one shot rather than this for loop?

Like some_task = fetch_all_conds(vals)

Not sure, if my question makes sense or not?

like image 663
frazman Avatar asked Nov 29 '18 04:11

frazman


1 Answers

First, your function makes no sense:

def check_cond(key):
    return True if key in some_dict else False

same simply: key in some_dict

Now: [val for val in vals if check_cond(val)] is the same as the intersection between the dict keys and vals, so your comprehension can be modified to:

[val for val in vals if val in some_dict]

If in vals there are not repeated values, you can:

 list(set(vals).intersect(some_dict.keys()))

For example:

>>> vals = [1, 2, 3]
>>> d = {1:1, 2:2, 4:4, 5:5}
>>> list(set(vals).intersection(d.keys()))
[1, 2]

You can use filter but is the same concept as the comprehension. We can even make the dict keys a set to make the lookup faster:

>>> def check_cond(keys, val):
...     return val in keys
... 
>>> from functools import partial
>>> result = list(filter(partial(check_cond, set(d.keys())), vals))
>>> 
>>> result
[1, 2]
like image 51
Netwave Avatar answered Sep 21 '22 19:09

Netwave