Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - intersect a dict and list

Tags:

python

Given the following data structures ,what is the most efficient way to find out the intersection - keys which are common to both the data structures.

dict1 = {'2A':'....','3A':'....','4B':.....}  
list1 = [......,'2A','4B'.....]

Expected output = ['2A','4B']

I am fine to organize the list(not dict1) into any other data-structure if that yields a faster output too. Since this lookup has 2 be done for a large number of dicts - speed is vital.

like image 710
IUnknown Avatar asked Feb 10 '26 12:02

IUnknown


2 Answers

As suggested by @Blckknght

>>> dict1.viewkeys() & list1
set(['4B', '2A'])

This has to be the fastest and most efficient way. Note that dict.viewkeys() is dict.keys in Python 3 (don't confuse this with Python 2 where dict.keys() returns a list instead)

like image 116
4 revsjamylak Avatar answered Feb 13 '26 01:02

4 revsjamylak


Use sets.

>>> set(dict1.keys()) & set(list1)
like image 44
BenDundee Avatar answered Feb 13 '26 03:02

BenDundee