Python - Intersection Between A List And Keys Of A Dictionary
I have a list that looks like this: l1 = ['200:200', '90:728'] I have a dictionary that looks like this: d1 = {'200:200':{'foo':'bar'},'300:300':{'foo':'bar'}} I need to get filt
Solution 1:
You can use the following code:
keys = set(l1).intersection(set(d1.keys()))
result = {k:d1[k] for k in keys}
EDIT: As commenters suggest you can replace the first line with, in Python 2.x:
keys = set(l1).intersection(d1)
And in Python 3.x:
keys = d1.keys() & l1
Solution 2:
In 3.x, this can be as simple as:
>>> {k: d1[k] for k in (d1.keys() & l1)}
{'200:200': {'foo': 'bar'}}
Under 2.7, you can use dict.viewkeys()
to recreate this functionality:
>>> {k: d1[k] for k in (d1.viewkeys() & l1)}
{'200:200': {'foo': 'bar'}}
Under older versions of 2.x, it's a tad more verbose:
>>> {k: d1[k] for k in (set(d1).intersection(l1))}
{'200:200': {'foo': 'bar'}}
Solution 3:
Not sure about each solution performance, but I would do:
{k: v for k, v in d1.items() if k in l1}
Solution 4:
Define efficient. Anyway here's what I would do. If it was too slow I'd probably move it to Cython.
s1 = set(l1)
s2 = set(d1.keys())
s3 = s1 & s2
# now you can access d1 using only keys in s3, or construct a new dict if you liked2 = dict([(k,d1[k]) for k in s3])
Solution 5:
If memory allocation and deallocation is making this process take too long, itertools to the rescue.
importitertoolsresult= {dict_key:d1[dict_key] for dict_key in itertools.ifilter(lambda list_item: list_item in d1, l1) }
This doesn't unnecessarily allocate memory for a whole new collection, and l1 could easily be an iterator instead of a list.
Post a Comment for "Python - Intersection Between A List And Keys Of A Dictionary"