-1

I made a dictionary using python

dictionary = {'key':'a', 'key':'b'}) 
print(dictionary)
print (dictionary.get("key"))

When run this code then shows the last value of dictionary, Is there any way to access the first value of dictionary if keys of both elements of dictionary are same.

hasnat ali
  • 11
  • 3

2 Answers2

1

In Python, multiple values cannot share the same key, unless each value is contained in a list or dictionary, mapped to each key. You can use a list instead:

dictionary = {'key':['a','b']}
print(dictionary["key"][0])

Output:

"a"
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

You cannot have the same key for a dictionnary (that's why it's called a key)

In [7]: dictionary = {'key':'a', 'key':'b'}

In [8]: print dictionary
{'key': 'b'}

You could use a list of tuple - depending on what you need to do : [ ('key', 'a'), ('key', 'b') ]

Francois
  • 515
  • 4
  • 14
  • Is there any way to access the first value of dictionary from memory? Because the first key and value is created of the dictionary in memory. – hasnat ali Oct 15 '17 at 15:29
  • Dictionary are not ordered so there is no such things as first value - you definitely want to use list of pairs in your case as it is very easy to access the first element of a list. – Francois Oct 15 '17 at 15:29