Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary with lists as elements and its comparison

Tags:

python

If I have a dictionary with lists in it like this one:

dic = {"j" : ["a", "b", "c", "d", "e", "f", "g"], "a" : [ "h", "b", "f"], "c": ["g", "i"]}

How can I make a code that first checks if any of the dictionary keys exist as strings inside the value lists. If they do compare the values of these two keys and count the number of similarities.

For example, the final result in this dictionary will be:

{'a': 0, 'c': 0, 'j': 3}

1 Answers

The following code reports, for each key in d, how many times any associated item occurs among the top-level dictionary keys:

{key: sum((item in d) for item in d[key]) for key in d}
#{'Family': 1, 'House': 0}
like image 91
DYZ Avatar answered Aug 26 '26 02:08

DYZ



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!