Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return common values of dictionary values for specific keys?

I have a dictionary, which contains:

{'Key': ['File1', 'File2']}

where key corresponds to a word and files are the set of files that contain that word.

Suppose I have a dictionary:

{'banana': ['file1.txt', 'file2.txt', 'file3.txt'],
 'apple': ['file2.txt', 'file3.txt']}

and my query is banana apple. How do I compare values in such a way that I return only file2.txt and file3.txt?

like image 325
sand Avatar asked Dec 08 '25 06:12

sand


1 Answers

You can use the set.intersection to create the common elements, like this

>>> d = {'banana': ['file1.txt', 'file2.txt', 'file3.txt'],
...      'apple': ['file2.txt', 'file3.txt']}
>>> words = 'banana apple'
>>> set.intersection(*(set(d[word]) for word in words.split() if word in d))
{'file2.txt', 'file3.txt'}

Here, we are creating a generator expression, which gets all the files corresponding to the word and converts that to a set. We then unpack the genereator expression over the set.intersection function, which finds the set intersection of all the sets.

Edit: If your values of the dictionary are really sets, as you mentioned in the question

and files are the set of files that contain that word

then, the solution can be even faster, since we don't have convert the lists to sets. You can simply skip that and do

>>> set.intersection(*(d[word] for word in words.split() if word in d))
{'file2.txt', 'file3.txt'}

Important Edit

What if the dictionary had only banana and apple is not there and the input is banana apple? If you wanted to return an empty set in that case, then you just have to slightly modify the generator expression, like this

>>> set.intersection(*(set(d.get(word, set())) for word in words.split()))
{'file2.txt', 'file3.txt'}

Here, we use dict.get method to return a default value if the key is not found in the dictionary. So, if apple is not there in the dictionary, then we return an empty set which makes the result an empty set (because when you intersect any set with an empty set, the result will be an empty set).

like image 151
thefourtheye Avatar answered Dec 10 '25 20:12

thefourtheye