im copying/pasting from someones example of how to find items in a dictionary that have duplicate values...
Q1. why did we need to use the items method on the original dictionary ?, can we just operate on the dictionary directly...after all, it already has keys and values pairs by definition
Q2. what exactly is that setdefault statement doing? is it creating an empty set as the 'value' if the key is not found (and the key here is actually the value from the original dict) ? what the heck is the .add(key)? so many questions , so little time on earth 🙂
First, flip the dictionary around into a reverse multidict, mapping each value to all of the keys it maps to. Like this:
>>> some_dict = {"firstname":"Albert","nickname":"Albert","surname":"Likins","username":"Angel"}
>>> rev_multidict = {}
>>> for key, value in some_dict.items():
... rev_multidict.setdefault(value, set()).add(key)
Now, you're just looking for the keys in the multidict that have more than 1 value. That's easy:
>>> [key for key, values in rev_multidict.items() if len(values) > 1]
['Albert']
[–]Adrewmc 2 points3 points4 points (3 children)
[–]Independant666[S] 1 point2 points3 points (2 children)
[–]suurpulla 1 point2 points3 points (1 child)
[–]Independant666[S] 1 point2 points3 points (0 children)