Can a dictionary have two keys of the same value?


Can a dictionary have two keys with the same value?


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. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


That each key should be unique is easy to understand. The keys of a dictionary themselves form set so each will have their own unique name. However, the values are not bound by this rule. Every key can have the same value associated with it. Values do not comprise a set of anything. They are plain data. It’s the keys that are unique. If a new value is assigned to a key that exists already, it will overwrite the old value.


We can try this example:

dictionary = {"key_1": "value_1", "key_1": "value_2", "key_2": "value_2"}
print(dictionary) # {'key_1': 'value_2', 'key_2': 'value_2'}

Just to be clear, keys (that is, key names) cannot be duplicated. As earlier stated, subsequent entries will overwrite the previous one. However, we can have several keys that all have the same value associated with them.


Hello ,
I have a question , In php we have arrays and associative arrays , which both are the same data types , instead later use our given keys instead of default numeric index , array use automatically

my_array = ["one", "two", "three"]  #indexes 0 , 1, 2
my_associative_array = ["one_index" => "one", "second_index" => "two", "third_index" => "three"]

I see array in php is similar to list in python and array in JS
and associative arrays in php is similar to objects in JS and dictionaries in python

are they different ways of syntax ing and naming same idea ?

Every language will have its own means of identifying and accessing data structures. There will be similarities but we should confine ourselves to the language we are using and the syntax prescribed.


Alright, we get that the keys have to be unique at all costs, but values that correspond to different keys need not be different. Now, I have a question. Can a particular key, say key_2, have more than 1 values stored in them ?? Just as if it was a real English Oxford Dictionary, where a word may have more than 1 meaning, for example: “fall” can mean “fall down” or “the season of fall” or “downfall” or “waterfall” etc…

Yes, they can. A value can be a sequence.

>>> dic = {
    'attr_1': (1, 1, 2, 3, 5, 8, 13)
>>> dic
{'attr_1': (1, 1, 2, 3, 5, 8, 13)}

We cannot write a non-contained sequence in this instance, though, like we can in a statement…

>>> a = 1, 1, 2, 3, 5, 8, 13
>>> a
(1, 1, 2, 3, 5, 8, 13)

The value can also be a dict, set, list or as above, a tuple. The latter is immutable.

1 Like

Great, that clears my doubt. Thank you for your time and knowledge…

1 Like