Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way of using has_key() inside filter()?

I know this is a very efficient way in python 2, to intersect 2 dictionaries

filter(dict_1.has_key, dict_2.keys())

However has_key() was removed from Python3, so I can't really use the fast filter() and has_key() functions. What I'm doing right now is:

[key for key in dict_2 if key in dict_1]

But it seems a bit janky, on top of not being so much readable. Is this really the new fastest way with python3, or is there a faster, cleaner way by using filter()?

like image 866
NaturalBornCamper Avatar asked Dec 30 '25 01:12

NaturalBornCamper


1 Answers

Instead of has_key in Python 2, you can use the in operator in Python 3.x. With filter, which gives a lazy iterator in 3.x, you can use dict.__contains__. There's also no need to call dict.keys:

res = filter(dict_1.__contains__, dict_2)    # lazy

print(list(res))
# [2, 3]

An equivalent, but less aesthetic, lambda-based solution:

res = filter(lambda x: x in dict_1, dict_2)  # lazy

A generator expression is a third alternative:

res = (x for x in dict_2 if ix in dict_1)    # lazy

For a non-lazy method, you can use set.intersection (or its syntactic sugar &):

res = set(dict_1) & set(dict_2)              # {2, 3}
like image 171
jpp Avatar answered Jan 01 '26 15:01

jpp