Dictionaries in Python provide a way to store the key-value pairs. In this article, we will see how to access the dictionary elements by index in Python even though they are unordered.

It is important to note that the items in the dictionary are unordered. When we retrieve the keys of the dictionary using the keys() method or by directly accessing an keys attribute, it returns an object which represents a dynamic view of the dictionary’s keys.

How to access them using the index?

The dictionary object is not indexable or sortable due to its unordered nature, but we can access its elements by index using the list() function or by converting it into the list explicitly.

Assume we have a dictionary my_dict. We can use the keys() method to retrieve the keys of this dictionary.

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
keys = my_dict.keys()

Now, to access the keys using the index, Conver the keys to the list using the list() method.

key_list = list(keys)

Finally, we can access the elements by index using the standard list indexing.

first_key = key_list[0]
second_key = key_list[1]

You should always keep in mind that dictionaries are unordered, so the order of the elements in the key_list may not match the order of insertion.

Following is the complete example which shows how to access the dictionary elements by index

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
keys = my_dict.keys()
key_list = list(keys)

first_key = key_list[0]
second_key = key_list[1]

print("First key:", first_key)
print("Second key:", second_key)

Categorized in:

Tagged in: