Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - intersection between a list and keys of a dictionary

Tags:

python

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

like image 887
Tampa Avatar asked Jun 22 '12 14:06

Tampa


People also ask

Can lists be keys in dictionaries?

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.

How do you intersect two sets in Python?

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.


1 Answers

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
like image 86
JPvdMerwe Avatar answered Oct 27 '22 01:10

JPvdMerwe