CM9 CM9 - 4 years ago 100
Python Question

Comparing Values in a Single Dictionary - Python

Say we have a dictionary that contains a list of words:

temp = {"1": "hello", "2": "goodbye", "3": "hello", "4": "goodbye", "5": "hi"}


I need help figuring out how to compare the values of each key. I understand I need to iterate through each but I can't figure out how to compare values of "1" to "2", and so on.

Output should be:

"1" == "3"
"2" == "4"
"5" ==


Thanks in advance.

Answer Source

You could do the following. Collect all keys for each in dict (or defaultdict) of lists:

from collections import defaultdict

temp = {"1": "hello", "2": "goodbye", "3": "hello", "4": "goodbye", "5": "hi"}
d = defaultdict(list)
for k, v in temp.items():
    d[v].append(k)

for k in d:
    print ' = '.join(repr(v) for v in d[k])  # repr only necessary to display quotes
    # print ' = '.join(d[k])
'5'
'1' = '3'
'2' = '4'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download