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 filter out the dictioary where only the keys are in l1. The dict should look like this:
result = {'200:200':{'foo':'bar'}}
In essence a intersection of a list and the keys of a dict while returning the subsection of the dict.
How do I do this efficiently where time is an issue for a large sets?
Thanks
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
Python Set intersection() Method The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With