2

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.

2 Answers 2

8

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)

11
  • 2
    It's worth noting that in Python 3, viewkeys has been renamed keys (and the original keys method doesn't exist any more). Furthermore, you can get even more concise using the & operator: dict1.viewkeys() & list1
    – Blckknght
    May 16, 2013 at 1:47
  • @Blckknght I assumed that wouldn't work because it doesn't work with normal sets, any reason why that behaviour is enabled in this case (eg. it works for non-sets)?
    – jamylak
    May 16, 2013 at 1:53
  • 1
    The dictionary key view type has an __and__ (and __rand__) operator that accepts any sequence as its second argument. I think sets used to accept arbitrary sequences for those operations too, but apparently they don't any more. I'm not sure if it's a bug or not that the two types don't have the same limitations.
    – Blckknght
    May 16, 2013 at 2:12
  • Note that intersection(dict1.viewkeys()) has the same effect as the simpler intersection(dict1), since intersection() accepts an iterable, and iterating over a dictionary returns its keys. May 16, 2013 at 4:09
  • 1
    @EOL: What I think is somewhat buggy is that the dictionary key view type doesn't precisely replicate the set (or frozenset) interface. Its API is very similar, but not the same. It would make a lot more sense for it to match set by having an intersection method that accepts arbitrary sequences, and for its __and__ operator to reject non-set sequences.
    – Blckknght
    May 16, 2013 at 4:24
2

Use sets.

>>> set(dict1.keys()) & set(list1)
1
  • 1
    set(dict1.keys()) is the same as set(dict1). May 16, 2013 at 4:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.