Reputation: 515
I need help trying to write a function for detecting if there is a dictionary which contains multiple keys. So im stuck since when using name_to_age the dictionary will already be unique so I am not sure how I can apply this check.
for e.g
# the test function should raise an error since there is 2 duplicate keys
name_to_age = {'Sam': 2, 'Sam': 4, 'Alex: 14}
Upvotes: 0
Views: 23303
Reputation: 13158
The original question is about writing a function that can detect duplicate keys in a dictionary. Strictly speaking, a dictionary cannot contain duplicate keys but it can contain objects with identical values: Multiple identical keys in a Python dict - yes, you can!
The trick is to use objects instead of strings as keys, and to override the hash comparison (see How hash collisions are resolved in Python dictionaries):
class person(object):
def __init__(self,name):
self.name = name
def __eq__(self, other):
return False
alternate = {person("Andrew") : "Cambridge", person("Barbara") : "Bloomsbury", person("Andrew"): "Corsica"}
print alternate
The comments below debate the technical aspects of whether these are duplicate keys or not, but this is a side issue. Back to the original question, if a dictionary could actually hold duplicate keys, what function would detect them?
To find duplicate keys, you could do this:
def list_duplicates(d):
seen = set()
duplicates = set( x.name for x in d if x.name in seen or seen.add(x.name) )
return list( duplicates )
(adapted from another question: Find and list duplicates in Python list)
Yes, multidict and querydict structures create lists of values for each key, but those don't address the original question's supposition of duplicate keys. This answer creates a scenario where duplicate "keys" are possible and provides a function to detect them.
Upvotes: 1