7

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?

frazman
  • 32,081
  • 75
  • 184
  • 269
  • 1
    Your question doesn't make sense to me. What is your goal with `some_task`? Can you give a concrete example? – slider Nov 29 '18 at 04:50
  • 1
    Your `check_cond()` is simply reinventing the old 2.x `dict.has_key()`, or these days in 3.x `if key in dict`. Related: [Should I use 'has_key()' or 'in' on Python dicts?](https://stackoverflow.com/questions/1323410/should-i-use-has-key-or-in-on-python-dicts) – smci Nov 29 '18 at 06:40
  • 1
    Your code can be replaced with `functools.filter(lambda key: key in d, vals)`. Not sure why you'd call it `some_task` though, it's just a filtered list of values. – smci Nov 29 '18 at 06:43

1 Answers1

5

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]
Netwave
  • 40,134
  • 6
  • 50
  • 93