Can a dictionary repeat identical keys or values?

Question,

What happens in a dictionary if you have repeated keys or repeated values?

Answer

Each of these is a separate case. Multiple keys can all have the same value as demonstrated below. This causes no issues.

>>> my_dict = { 'key' + str(x+1): 0 for x in range(10) }
>>> my_dict
{'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 0, 'key6': 0, 'key7': 0, 'key8': 0, 'key9': 0, 'key10': 0}
>>> 

However you cannot have identical keys within a dictionary. Attempting to create a second identical key will simply overwrite the first as shown below.

>>> my_dict = { 'key': x for x in range(10) }
>>> my_dict
{'key': 9}
>>> 

Special reminder that 6 is not the same as '6' as one is numeric and the other a string, so if these were each a key they would be unique from each other.

Credit for examples used goes to @mtf.

So does a dictionary have say separate indexes for keys and if possible separate indexes for values?? Can we think of a dictionary being a data structure which is indexed like LISTS or STRINGS or TUPLES ???

1 Like

Short answer, no. If you want a structure you can access by index like a list, use list.

2 Likes

Alright, that clears the doubt. Thank you for helping me out…

1 Like

You can view this thread for a longer answer.
You can for example do this:

myDict = {'a': 1, 'b': 2, 'c': 3}
print(list(myDict.keys())[1]) #prints b
print(list(myDict.values())[1]) #prints 2
print(list(myDict.items())[1]) #prints ('b', 2)
5 Likes

I dont get this bit :frowning:

x for x in range(10) → won’t it iterate from 0 to 9?
How come it only return 9?

Thanks!

Because you cannot have duplicate keys in a dictionary. It does iterate from 0 to 9, but each time it overwrites the previous value for the key named 'key'. Since 9 is the last value written, it is the only value assigned to 'key'.

This would produce a dictionary with 10 keys:

>>> dict = {f'key{x}' : x for x in range(10)}
>>> dict
{'key0': 0, 'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5, 'key6': 6, 'key7': 7, 'key8': 8, 'key9': 9}
12 Likes

oooooooh I see!!

Thank you!!

1 Like

Why we are using list bracket to fetch values from the dictionaries?

my_list = {“tom”: 32}

why can’t use this

print(my_list{tom})

else of using

print(my_list[tom])

Square brackets, rather than list brackets, would be a better term for []. [] is not used solely for lists, but is also used to retrieve the value at a certain index or key of an iterable object (like a list, dictionary, tuple, etc.).

Whenever we want to get the value at a certain index or key of any iterable object (not only lists), we use square brackets like so.

iterable[index_or_key]
3 Likes

Thank you! Now i get it.
I’ll remember to call them Square brackets. XD

1 Like