What is the usage of indexing in Python dictionaries?

In Python, dictionary indexing is used to retrieve the corresponding value in the dictionary by using a key. Dictionaries are an unordered data type consisting of keys and their corresponding values, where the keys can be used to index and fetch the corresponding values.

For example, there is a dictionary called “person” that represents information about a person.

person = {'name': 'John', 'age': 25, 'city': 'New York'}

To obtain the value corresponding to a specific key in the dictionary, you can use square brackets [] for indexing.

name = person['name']
age = person['age']

In the example above, person[‘name’] will return the value ‘John’ for the key ‘name’ in the dictionary person, and person[‘age’] will return the value 25.

It’s important to note that if you try to index a dictionary with a key that doesn’t exist, it will raise a KeyError exception. You can use the get() method to avoid this exception. For example:

city = person.get('city', 'Unknown')

The above code will return the value of the key ‘city’ in the dictionary as ‘New York’, and if the key does not exist, it will return the default value ‘Unknown’.

bannerAds