-3

Suppose python dictionary is like D = {'a':1,'a':2} Can I get those 2 values with same key Because I want write a function so I can get dictionary like above?

Lokesh Harad
  • 11
  • 1
  • 1
  • 1
  • 2
    You can't. Keys have to be unique. – Thierry Lathuille Oct 18 '19 at 16:47
  • If you search in your browser for "Python dict tutorial", you'll find references that can explain this much better than we can manage here. By definition, dict keys are unique. – Prune Oct 18 '19 at 16:47
  • No, `dict` objects must have unique keys. In an expression like `D = {'a':1,'a':2}`, the dict is constructed taking the last key-value pair with the non-unique key, from left to right. so it will simply evaluate to `{'a':2}` – juanpa.arrivillaga Oct 18 '19 at 16:47

2 Answers2

1

Dictionary keys in Python are unique. Python will resolve D = {'a':1,'a':2} as D = {'a': 2}

You can effectively store multiple values under the same key by storing a list under that key. In your case,

D = {'a': [1, 2]}

This would allow you to access the elements of 'a' by using

D['a'][elementIdx]   # D['a'][0] = 1
schwadan
  • 148
  • 10
0

You cannot. I set up an identical dictionary, and when attempting to print the key 'a', I received the secondary value, i.e., 2. Keys are meant to be unique.

You could try something like:

x = {}
for i in range(2):
    x[f"a{i}"] = i

Which would output key values like a0, a1, etc.

Mochamethod
  • 276
  • 4
  • 14