In this Python tutorial, we’ll learn about Python nested dictionary in detail. We’ll see how to create a nested dictionary, fetch data from it, update, delete and add data with the help of proper practical Python code examples.
Introduction: Python Nested Dictionary
It specifies dictionary(one or more) inside a dictionary. Let’s first understand its syntax, then we’ll see how to properly implement it in Python programs.
Syntax of Nested Dictionary
dictionary={ 'a':{'x':34,'y':432}, 'b':{'i':'Zeeshan,'j':1.45} }
We can see dictionary has been used as value in key, value pair inside a dictionary. This is how nested dictionaries can be specified.
Implementing Python Nested Dictionary (Easy Examples)
Now in order to properly understand how to use Python nested dictionary, we’ve to go through all the examples specified below.
Example 1: Creating a Nested Dictionary
nesteddict = {'names':{'name1':'Zeeshan','name2':'Yasir'},'age':{'age1':25,'age2':25}} print(nesteddict)
Output
{'names': {'name1': 'Zeeshan', 'name2': 'Yasir'}, 'age': {'age1': 25, 'age2': 25}}
We’ve created a nested dictionary and inside it, we’ve specified 2 items(key, value pairs). We’ve passed dictionaries as values in both these pairs. In this case, nesteddict is a Python nested dictionary. So this is how we can created a nested dictionary. We can specify more/less pairs as well.
Example 2: Fetch Data From Python Nested Dictionary
nesteddict = {'name':{'n1':'Zeeshan','n2':'Yameen'},'age':{'ag1':25,'ag2':26}} print(nesteddict['name']['n1'])
Output
Zeeshan
In order to access elements from nested dictionary, we’ve to use the indexing([]) method. For demonstration, we’ve fetched data from inside dictionary.
We can see that first we’ve to use the key inside square brackets like this, [‘name’]. Then we’ve to specify the key of inside dictionary in the second square brackets like this, [‘n1’]. As a result, value of this key has been displayed and it can be seen in the above output section.
We can access other values using the same process. Let’s try it with other values as well. See below:
print(nesteddict['name']['n2']) print(nesteddict['age']['ag1']) print(nesteddict['age']['ag2'])
Output
Yameen 25 26
Example 3: Add Item
nesteddict = {'item1':{'a':1,'b':2},'item2':{'x':10,'y':20}} nesteddict['item2']['r']='Zeeshan' print(nesteddict)
Output
{'item1': {'a': 1, 'b': 2}, 'item2': {'x': 10, 'y': 20, 'r': 'Zeeshan'}}
We’ve to use the same indexing method in order to add items to the inside dictionary. It’ll first see if the specific key is present or not. If yes, then it’ll replace its value. If not present then it’ll add a new key value pair from the specified data(key, value).
For demonstration, we’ve specified a key that is not present in the dictionary and we can see that its been added as an new key, value pair.
Example 4: Update Existing Item
nesteddict = {'i1':{'a':11,'b':22},'i2':{'x':100,'y':200}} nesteddict['i1']['a']='Zee' print(nesteddict)
Output
{'i1': {'a': 'Zee', 'b': 22}, 'i2': {'x': 100, 'y': 200}}
We can see that we’ve to use the same indexing method for it as well. For demonstration, we’ve specified an existing key of the inside dictionary and have assigned a value to it. Then printing the nested dictionary shows the updated value and it can be seen in the above output section.
We can update the whole inside dictionary as well. See below code:
nesteddict['i1']='Zee' print(nesteddict)
Output
{'i1': 'Zee', 'i2': {'x': 100, 'y': 200}}
We can do the same process to add new item (example 3) as well. We just have to specify a key that is not present in the dictionary and assign it some value.
Example 5: Delete Item/Dictionary From Nested Dictionary
nDict = {'professions':{'x':'Freelancer','y':'Gov. Official'}} del nDict['professions']['x'] print(nDict)
Output
{'professions': {'y': 'Gov. Official'}}
In order to remove/delete item from dictionary, we’ve to use the del statement. For demonstration, we’ve specified the del statement and after that, we’ve specified the item to be removed using the indexing method. Printing the dictionary after applying it shows that the items has been successfully removed.
We can also delete multiple items in the same line. We’ve to separate them using comma(,). See below:
del nDict['professions']['x'], nDict['professions']['y'] print(nDict)
Output
{'professions': {}}
We can also remove the whole dictionary. See below code:
del nDict['professions'] print(nDict)
Output
{}
It shows an empty dictionary because we had only one key value pair and we’ve removed this key using the del statement. We can also remove multiple key value pairs using the same above method. We just have to put comma(,) between them.
Example 6: Nested Dictionary With Python For Loop
dictVals={'names':{'nam1':'Yameen','nam2':'Yasir'},'ids':{'nam1_ID':345,'nam2_ID':857}} newDict={} for id,data in dictVals.items(): print('ID: ',id) for value in data: print(value,': ',data[value]) newDict[id]=data print(newDict)
Output
ID: names nam1 : Yameen nam2 : Yasir ID: ids nam1_ID : 345 nam2_ID : 857 {'names': {'nam1': 'Yameen', 'nam2': 'Yasir'}, 'ids': {'nam1_ID': 345, 'nam2_ID': 857}}
- In this program, we have iterated over Python nested dictionary using for loop.
- We’ve first created a Python nested dictionary.
- Also, we’ve specified an empty dictionary to store the resulting values.
- Then we’ve specified a Python for loop which have 2 variables. First variable stores the keys(names, ids) and second one stores the values of these keys(dictionaries).
- Inside the body of for loop, we’ve first printed the keys so in every iteration, keys will be printed first.
- We’ve used nested for loop which will iterate over the values of inner dictionary. We’ve showed the values using indexing([]) method.
- We also have stored the values in new list and displayed it. The result can be seen in the output block.
Important Note
Some important points about nested dictionaries are given below.
- Unordered collection of dictionary.
- Slicing is not possible.
- Can shrink or grow.
- Contains keys and values like a normal dictionary.
- Accessible using keys.
We’ll be super glad if by reading this post, you have gained knowledge of Python nested dictionary. We’d be very happy to see you share this knowledge with other Python programmers.
Don’t hesitate to ask if you still have questions regarding Python nested dictionary. We’ll be very happy to help you.
Conclusion
To conclude this tutorial, hope now you’ll be able to easily implement Python nested dictionary in your own Python programs. Please don’t forget to leave your valuable feedback in the comment section.
Other worth reading posts on Python programming are also posted on this site. Feel free to pay a visit to them as well. Thank you for reading this article.