-1

how to get access of elements of a dictionary base on its index. for example i have this dictionary with name 'a' :

a={'ali':10 , 'reza':19 , 'sara':15}

is there any way to get access of first or second or third value of dictionary directly? i mean, i dont want to use these below codes.

a['ali'] or a['reza'] or a['sara'] 

i want to get first/second/third value of above dict directly. despite i know this is wrong but assume for example i use this code and get access of values by its index :

a[0]  ====>   10  or   a[1]  ====>   19

please help me to solve this problem.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
alireza
  • 113
  • 6

2 Answers2

1

You need to convert the keys of the dictionary to a list in order to access by its index. This method has an O(n) complexity compared to the access by key values directly to the dictionary (hash table), which results in a constant O(1) time complexity:

a={'ali':10 , 'reza':19 , 'sara':15}
print(a[list(a.keys())[0]]) #Here you are getting a list of all keys of the dictionary by calling list(a.keys()), and accessing a specific element of that list with [:] operator

Output:

10
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
-1

Dictionaries aren't indexed, so no. They're associative, that is, you access elements by their keys. If you want an ordered collection, you need to use a list or a tuple.

ndc85430
  • 1,395
  • 3
  • 11
  • 17