Nested Dictionary in Python

 


Nested Dictionary

A dictionary can contain dictionaries, this is called nested dictionaries.

Example 1

Create a dictionary that contain three dictionaries:

Student = {
  
"Manoj" : {
    
"Roll" : "102",
    
"Marks" : 300
  },
  
"Monu" : {
    
"Roll" : "103",
    
"Marks" : 326
  },
  
"Sonu" : {
    
"Roll" : "104",
    
"Marks" : 298
  }
}

Print(Student)

Output:

{‘Manoj’: {‘Roll’: ‘102’, ‘Marks’: 300}, ‘Monu’: {‘Roll’: ‘103’, ‘Marks’: 326}, ‘Sonu’: {‘Roll’: ‘104’, ‘Marks’: 298}}

Example 2

family = {
  
"child1" : {
    
"name" : "Monu",
    
"year" : 2004
  },
  
"child2" : {
    
"name" : "Rohit",
    
"year" : 2007
  },
  
"child3" : {
    
"name" : "Ashu",
    
"year" : 2011
  }
}

Print(family)

Output:

{'child1': {'name': ‘Monu’, 'year': 2004}, 'child2': {'name': ‘Rohit’, 'year': 2007}, 'child3': {'name': ‘Ashu’, 'year': 2011}}

Or, if you want to add three dictionaries into a new dictionary:

Example 3

Create three dictionaries, then create one dictionary that will contain the other three dictionaries:

child1 = {
  
"name" : "Monu",
  
"year" : 2004
}
child2 = {
  
"name" : "Rohit",
  
"year" : 2007
}
child3 = {
  
"name" : "Ashu",
  
"year" : 2011
}

family = {
  
"child1" : child1,
  
"child2" : child2,
  
"child3" : child3
}

Print(family)

Output:

{'child1': {'name': ‘Monu’, 'year': 2004}, 'child2': {'name': ‘Rohit’, 'year': 2007}, 'child3': {'name': ‘Ashu’, 'year': 2011}}

<<Previous                                                  Next>>

कोई टिप्पणी नहीं

टिप्पणी: केवल इस ब्लॉग का सदस्य टिप्पणी भेज सकता है.

Microsoft Word top 180 keyboard shortcuts

Microsoft Word top 180 keyboard shortcuts Download shortcut keys File: MS Word File - Click here MS Excel File - Click here PDF File - Click...

Blogger द्वारा संचालित.