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?
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}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With