How to access elements of a nested dictionary in Python
In this tutorial, you will learn how to form a dictionary and access elements of a nested dictionary to change it according to the need of the user.
In Python, how can we access elements of the nested dictionary?
Syntax:
dictionary = {'key_1' : 'value_1', 'key_2' : 'value_2'}
Here, the dictionary has a key : value pair enclosed within curly brackets (“{}”).
Nested Dictionary:
Syntax:
nested_dict = { 'dictA': {'key_1' : 'value_1'}, 'dictB': {'key_2' : 'value_2'}}
Here, dictA and dictB are Nested Dictionaries.
Let’s create a Nested Dictionary:
people = {1: {'name' : 'CodeSpeedy', 'age' : '34'}, 2: {'name' : 'Yash', 'age' : '23'}} print(people)
Output:
{1: {'name': 'CodeSpeedy', 'age': '34'}, 2: {'name': 'Yash', 'age': '23'}}
People is a nested dictionary above. People are allocated to internal dictionaries 1 and 2. which have keys and values.
Until now we learned to create how to create a Nested Dictionary now let’s see how to access Nested Dictionary’s elements.
people = {1: {'name' : 'CodeSpeedy', 'age' : '34'}, 2: {'name' : 'Yash', 'age' : '23'}} print(people[1]['name']) print(people[2]['age'])
Output:
CodeSpeedy 23
Also read: How to call a Nested function: Python nested function Call!
Leave a Reply