This can happen if you violate a requirement of dict, and change its hash.

When an object is used in a dict, its hash value must not change, and its equality to other objects must not change. Other properties may change, as long as they don't affect how it appears to the dict.

(This does not mean that a hash value is never allowed to change. That's a common misconception. Hash values themselves may change. It's only dict which requires that key hashes be immutable, not __hash__ itself.)

The following code adds an object to a dict, then changes its hash out from under the dict. q[a] = 2 then adds a as a new key in the dict, even though it's already present; since the hash value changed, the dict doesn't find the old value. This reproduces the peculiarity you saw.

class Test(object):
    def __init__(self, h):
        self.h = h
    def __hash__(self):
        return self.h

a = Test(1)
q = {}
q[a] = 1
a.h = 2
q[a] = 2

print q

# True:
print len(set(q.keys())) != len(q.keys())
Answer from Glenn Maynard on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-unique-values-of-key-in-dictionary
Python - Unique Values of Key in Dictionary - GeeksforGeeks
July 12, 2025 - for loop iterates over each dictionary d in data and if the dictionary contains the key then the value is extracted. The condition if value not in seen checks whether the value has already been added. If not, it adds the value to both the seen set and the "res" list. We will use the reduce function from the functools module to accumulate unique values in an order-preserving manner, the lambda function checks if the value is new and then concatenates it to the accumulator list if it is.
Discussions

Keys are not unique for a python dictionary! - Stack Overflow
A new AI Addendum clarifies how Stack Overflow utilizes AI interactions. Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... A stupid newbie question here For a python dictionary q len(set(q.keys... More on stackoverflow.com
🌐 stackoverflow.com
hash - How To Create a Unique Key For A Dictionary In Python - Stack Overflow
What is the best way to generate a unique key for the contents of a dictionary. My intention is to store each dictionary in a document store along with a unique id or hash so that I don't have to l... More on stackoverflow.com
🌐 stackoverflow.com
Dictionary with non unique keys
Sounds like you need a dict of lists? Like {'key1': ['value1', 'value2']} More on reddit.com
🌐 r/learnpython
85
28
January 17, 2024
python - Unique dictionary values - print keys - Code Review Stack Exchange
I'm working on this code for exam in an MIT Python course. It's working but I'm trying to improve it. What could I do, and what should I avoid? aDict = { 0: 1, 1: 2, 2: 2, 4: 2... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 10, 2015
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-unique-value-keys-in-a-dictionary-with-lists-as-values
Python - Unique value keys in a dictionary with lists as values - GeeksforGeeks
April 27, 2023 - The original dictionary is : {'Gfg': [6, 5], 'best': [12, 6, 5], 'is': [6, 10, 5]} The unique values keys are : ['best', 'is'] Time Complexity: O(n), where n is the length of the list test_list Auxiliary Space: O(n) additional space of size ...
Top answer
1 of 2
17

This can happen if you violate a requirement of dict, and change its hash.

When an object is used in a dict, its hash value must not change, and its equality to other objects must not change. Other properties may change, as long as they don't affect how it appears to the dict.

(This does not mean that a hash value is never allowed to change. That's a common misconception. Hash values themselves may change. It's only dict which requires that key hashes be immutable, not __hash__ itself.)

The following code adds an object to a dict, then changes its hash out from under the dict. q[a] = 2 then adds a as a new key in the dict, even though it's already present; since the hash value changed, the dict doesn't find the old value. This reproduces the peculiarity you saw.

class Test(object):
    def __init__(self, h):
        self.h = h
    def __hash__(self):
        return self.h

a = Test(1)
q = {}
q[a] = 1
a.h = 2
q[a] = 2

print q

# True:
print len(set(q.keys())) != len(q.keys())
2 of 2
1

The underlying code for dictionaries and sets is substantially the same, so you can usually expect that len(set(d.keys()) == len(d.keys()) is an invariant.

That said, both sets and dicts depend on __eq__ and __hash__ to identify unique values and to organize them for efficient search. So, if those return inconsistent results (or violate the rule that "a==b implies hash(a)==hash(b)", then there is no way to enforce the invariant:

>>> from random import randrange
>>> class A():
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        return bool(randrange(2))
    def __hash__(self):
        return randrange(8)
    def __repr__(self):
        return '|%d|' % self.x


>>> s = [A(i) for i in range(100)]
>>> d = dict.fromkeys(s)
>>> len(d.keys())
29
>>> len(set(d.keys()))
12
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-get-all-unique-keys-from-a-list-of-dictionaries
Get all Unique Keys from a List of Dictionaries - Python - GeeksforGeeks
February 5, 2025 - We use itertools.chain() to chain the keys from all dictionaries into a single iterable. from_iterable() allows us to flatten the iterable of key lists into a single sequence and we then convert the result into a set to ensure all keys are unique.
🌐
GeeksforGeeks
geeksforgeeks.org › python-unique-values-of-key-in-dictionary
Python – Unique Values of Key in Dictionary | GeeksforGeeks
February 10, 2025 - For each dictionary d, the lambda checks if the key exists and if its value is not already in acc; if true then it concatenates [d[key]] (a single-item list) to acc. ... Given a Dictionaries list, the task is to write a Python program to count the unique values of each key.
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-get-all-unique-keys-from-a-list-of-dictionaries
Extract Unique dictionary values in Python Program
my_dict = {'hi' : [5,3,8, 0], 'there' : [22, 51, 63, 77], 'how' : [7, 0, 22], 'are' : [12, 11, 45], 'you' : [56, 31, 89, 90]} print("The dictionary is : ") print(my_dict) my_result = list(sorted({elem for val in my_dict.values() for elem in val})) print("The unique values are : ") print(my_result)
Find elsewhere
🌐
LabEx
labex.io › tutorials › python-how-to-ensure-dictionary-key-uniqueness-461886
Python - How to ensure dictionary key uniqueness
A dictionary in Python is a versatile data structure that stores key-value pairs. It allows you to create collections of items where each item is uniquely identified by its key.
🌐
Reddit
reddit.com › r/learnpython › dictionary with non unique keys
r/learnpython on Reddit: Dictionary with non unique keys
January 17, 2024 -

Im not entirely new to python but Im having a problem that I cant quite seem to find the answer to.

What I have is a dictionary that ofcourse have keys and values. Only the keys arent unique ( and shouldnt be ) But what I need is essentially this:

I input a key string. What I need returned is every value that match that key.
Problem is that using regular dictionary it only returns the first value. Not all of them.
Should I be looping through the return to get all the values ? I tried looking but it doesnt seem like dictionary returns a tuple when having multiple values. Is there an easy way to output every match of the key ?

🌐
TestDriven.io
testdriven.io › tips › b4e36507-fd5e-4bbd-abe2-c2530e8c044f
Tips and Tricks - Get the unique values from a list of dictionaries | TestDriven.io
Python tip: You can use a dictionary comprehension to create a list of dictionaries unique by value on a selected key · users = [ {"name": "John Doe", "email": "[email protected]"}, {"name": "Mary Doe", "email": "[email protected]"}, {"name": "Mary A. Doe", "email": "[email protected]"}, ] print(list({user["email"]: user for user in users}.values())) """ [ {'name': 'John Doe', 'email': '[email protected]'}, {'name': 'Mary A.
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-20.php
Python: Print all unique values in a dictionary - w3resource
L = [{"V": "S001"}, {"V": "S002"}, ... the code section. print("Original List: ", L) # Create a set 'u_value' to store unique values found in the dictionaries within the list 'L'. # Use a set comprehension to iterate through the ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › 15 things you should know about dictionaries in python
15 things you should know about Dictionaries in Python | Towards Data Science
March 5, 2025 - A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,).
Top answer
1 of 3
4

Yes, you can use the defaultdict:

Sample code:

»»» from collections import defaultdict

»»» mydict = defaultdict(list)

»»» letters = ['a', 'b', 'a', 'c', 'a'] 

»»» for l in letters:
   ....:     mydict[l].append('1')
   ....:     

»»» mydict
Out[15]: defaultdict(<type 'list'>, {'a': ['1', '1', '1'], 'c': ['1'], 'b': ['1']})

If you need the content to be initialised to something fancier, you can specify your own construction function as the first argument to defaultdict. Passing context-specific arguments to that constructor might be tricky though.

2 of 3
2

The solution provided by m01 is cool and all but I believe it's worth mentionning that we can do that with a plain dict object..

mydict = dict()
letters = ['a', 'b', 'a', 'c', 'a']

for l in letters:
    mydict.setdefault(l, []).append('1')

the result should be the same. You'll have a default dict instead of using a subclass. It really depends on what you're looking for. My guess is that the big problem with my solution is that it will create a new list even if it is not needed.

The defaultdict object has the advantage to create a new object only when something is missing. This solution has the advantage to be a simple dict without nothing special.

Edit

After thinking about it, I found out that using setdefault on a defaultdict will work as expected. But it's not yet good enough to say that a plain old dict should be used instead. There are cases where having a dict is important. To make it short, an invalid key on a dict will raise a KeyError. A defaultdict will return a default value.

As an example, there is the traversal algorithm that stops whenever it catches a KeyError or it traversed a whole path. With a defaultdict, you'd have to raise yourself the KeyError in case of errors.

🌐
Codecademy Forums
discuss.codecademy.com › frequently asked questions › python faq
Can a dictionary have two keys of the same value? - Python FAQ - Codecademy Forums
August 4, 2018 - Question Can a dictionary have two keys with the same value? Answer No, each key in a dictionary should be unique. You can’t have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.