Python - How To Python Dictionary Index

ID : 194

viewed : 106

Tags : PythonPython Dictionary

vote vote


Dictionaries are used for storing key-value pairs in Python. In general, we cannot access a dictionary using the index of their elements for other collections like a list or an array.

Before Python 3.7, dictionaries were orderless. Each key-value is given a random order in a dictionary. We can use the OrderedDict() method from the collections module in these cases. It preserves the order in which the key-value pairs are added to the dictionary.

In Python 3.7 and up, the dictionaries were made order-preserving by default.

We can access the keys, values, and key-value pairs using the index in such dictionaries where the order is preserved.

Access the Keys From a Dictionary Using the Index

We will use the keys() method, which returns a collection of the keys. We can use the index to access the required key from this collection after converting it to a list.

Remember to use the list() function with the keys(), values() and items() function. It is because that they do not return traditional lists and do not allow access to elements using the index.

The following demonstrates this.

d = {}  d['a'] = 0 d['b'] = 1 d['c'] = 2 keys = list(d.keys()) print(keys[1]) 



When working below Python 3.7, remember to use the OrderedDict() method to create the required dictionary with its order maintained. For example,

from collections import OrderedDict d1 = OrderedDict()  d1['a'] = 0 d1['b'] = 1 d1['c'] = 2 keys = list(d1.keys()) print(keys[1]) 



Access the Values From a Dictionary Using the Index in Python

When we want to return a collection of all the values from a dictionary, we use the values() function.

d = {}  d['a'] = 0 d['b'] = 1 d['c'] = 2 values = list(d.values()) print(values[1]) 



Access the Key-Value Pairs From a Dictionary Using the Index in Python

The items() function returns a collection of all the dictionary’s key-value pairs, with each element stored as a tuple.

The index can be used to access these pairs from the list.

d = {}  d['a'] = 0 d['b'] = 1 d['c'] = 2 values = list(d.items()) print(values[1]) 


('b', 1) 

Remember to use the OrderedDict() function with all the methods if your version of Python doesn’t preserve the order of the dictionary.

  • Related HOW TO?