Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter dictionary from array values

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?


2 Answers

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}
like image 97
Dani Mesejo Avatar answered Jun 17 '26 08:06

Dani Mesejo


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}
like image 33
sacuL Avatar answered Jun 17 '26 07:06

sacuL