Reputation:
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?
Upvotes: 3
Views: 2229
Reputation: 12990
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}
Upvotes: 0
Reputation: 51395
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}
Upvotes: 1
Reputation: 78750
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}
Upvotes: 0
Reputation: 61910
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}
Upvotes: 6