3

I have a dictionary which has values as follows:

dictionary = {(10,9): 1, (44,11): 2, (1,1): 99}

Basically my keys are pairs of integers and the values of each key are just integers.

I have an array which stores a set of keys:

array = [(1,1), (5,19), (58,7)]

I would like to filter my dictionary to contain only elements which keys are stored in the array. In my case, after filtering the dictionary I would obtain the following:

dictionary = {(1,1): 99}

since the only key of the dictionary which is stored in the array is (1,1)

What would be the most efficient way to do this?

Ayman
  • 580
  • 9
  • 27
  • Possible duplicate of [filter items in a python dictionary where keys contain a specific string](https://stackoverflow.com/questions/23862406/filter-items-in-a-python-dictionary-where-keys-contain-a-specific-string) – Bill the Lizard Oct 26 '18 at 19:34

4 Answers4

6

You could do something like this:

dictionary = {(10,9): 1, (44,11): 2, (1,1): 99}
array = [(1,1), (5,19), (58,7)]

result = { k:v for k, v in dictionary.items() if k in array}

Output

{(1, 1): 99}

Or even faster, transforming the list into a set:

s = set(array)
result = {k: v for k, v in dictionary.items() if k in s}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

You could find the set intersection of the dictionary keys and the array tuples, then get your new values in a dict comprehension. This will reduce the complexity of searching for each key in your array:

dictionary = {(10,9): 1, (44,11): 2, (1,1): 99}
array = [(1,1), (5,19), (58,7)]

>>> {i:dictionary[i] for i in set(dictionary.keys()).intersection(array)}
{(1, 1): 99}
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

Here's a dict-comprehension:

>>> dictionary = {(10,9): 1, (44,11): 2, (1,1): 99}
>>> lst = [(1,1), (5,19), (58,7)]    
>>> d = {k:v for k,v in dictionary.items() if k in lst}
>>> {(1, 1): 99}

I renamed array to lst because it is a list. We should not confuse lists with numpy arrays, array.array or the bytearray type.

You could also write a traditional for loop if you are not yet comfortable with comprehensions:

>>> d = {}
>>> for key in dictionary:
...:    if key in lst:
...:        d[key] = dictionary[key]
...:        
>>> d
>>> {(1, 1): 99}
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

What about just:

res = {i: dictionary[i] for i in array if i in dictionary}

This does it in O(n) where n is the number of items in array and doesn't require any additional data structures.

For your dictionary and array, this gives us:

{(1, 1): 99}
slider
  • 12,810
  • 1
  • 26
  • 42