Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find common items from Python dictionary values?

Tags:

python

set

Say, I have a dictionary D:

D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}

Now I want to have all common items from D's values, which would be 2. I tried to use set.intersection but it did not work out.


1 Answers

Simply, use intersection method of set:

>>> set.intersection(*D.values())
{2}

D.values() will return a list of your dictionary values which are already sets, then *D.values() will unpack this list and pass it to intersection method of set class

like image 73
Iron Fist Avatar answered Sep 24 '26 09:09

Iron Fist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!