Tuesday, October 16, 2018

Nesting dictionaries and lists in Python

Storing a set of dictionaries in a list or a list of items as a value in a dictionary is known as Nesting. In Python it is possible to nest a set of dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary. Let us see these nesting one by one-

1. Creating a list of Dictionaries

The user1 dictionary we created in our previous post contains a variety of information about one user, but it cannot store information about a second user. How to manage a group of users? One way is to make a list of users in which each user is a dictionary of information about that user. Let's implement this example.

user1 = { 'username':'vswami',
          'first_name':'Vivek',
          'Last_name':'Swami',
          'email':'vswami@gmail.com',
          'middle_name':'Vivek',

            }
           
user2 = { 'username':'satya1278',
          'first_name':'Satya',
          'Last_name':'A',
          'email':'satya1278@gmail.com',
          'middle_name':'N',

            }
           
user3 = { 'username':'mnraj',
          'first_name':'Nagaraju',
          'Last_name':'M',
          'email':'mnraj@gmail.com',
          'middle_name':'K',

            }                       

users = [user1,user2,user3]

for user in users:
    print(user)



First  I've created three dictionaries, each representing a different user. Then I've packed each of these dictionaries into a list called users. Finally, I've used a for loop through the list and print out each user. The screen shot below shows the output of the above program-




2. Nesting a list in a Dictionary

We can nest a list inside a dictionary any time you want more than one value to be associated with a single key in a dictionary. For example if we want to display favorite books of the programmers in your team. We will store each person’s responses in a list, people could choose more than one favorite book. When we loop through the dictionary, the value associated with each person would be a list of books rather than a single book. Inside the dictionary’s for loop, we use another for loop to run through the list of books associated with each person. Let's implement this example-

favorite_books = {

                    'satya':['a','b','c'],
                    'raju':['d','e','f'],
                    'swami':['g','h','i','a','d','c'],
                   
                    }
                   
for name,titles in favorite_books.items():  
   
   
    print("\n" + name.title() + "'s favorite books are:")
   
    for title in titles:
        print("\t" + title.title())



As we can see from the program above the value associated with each name is now a list. Notice that different people have different  number of favorite books. When we first  loop through the dictionary we use the variable titles to hold each value from the dictionary, because we know that each value will be a list. Inside the main dictionary loop, we use another for loop to run through each person’s list of favorite books. Now each person can list as many favorite languages as they like. The screen shot below shows the output of the above program-



3. Nesting a Dictionary in a Dictionary

Nesting a dictionary inside another dictionary makes our code complicated. If the structure of each user’s dictionary is identical, it makes nested dictionaries easier to work with. If each user’s dictionary had different keys, the code inside the for loop would be more complicated. Let's create a program to implement this.

We have several users for a website, each with a unique username, hence we can use the usernames as the keys in a dictionary. Then we  store information about each user by using a dictionary as the value associated with their username. See the program below-

users = {
          'vswami': {
          'first_name':'Vivek',
          'Last_name':'Swami',
          'email':'vswami@gmail.com',
          'middle_name':'K',

            },
           
          'satya1278':{
          'first_name':'Satya',
          'Last_name':'A',
          'email':'satya1278@gmail.com',
          'middle_name':'N',

            },
           
          'mnraj':{
          'first_name':'Nagaraju',
          'Last_name':'M',
          'email':'mnraj@gmail.com',
          'middle_name':'K',

            },
            }                       


for user_name, user_info in users.items():
   
    print("\nusername: "+user_name)
    full_name = user_info['first_name']+" "+user_info['middle_name']+" "+user_info['Last_name']
    email_id = user_info['email']
   
    print("\nFull Name: " + full_name.title())
    print("\nemail id: "+ email_id)




We first define a dictionary called users with three keys: one each for the usernames 'vswami' 'satya1278' and 'mnraj'. The value associated with each key is a dictionary that includes each user’s first name, last name, email and middle name.

Next we loop through the users dictionary. Python stores each key in the variable user_name, and the dictionary associated with each username goes into the variable user_info. Once inside the main dictionary loop, we print the username.

Next we start accessing the inner dictionary. The variable user_info,which contains the dictionary of user information, has four keys: 'first_name','Last_name', 'email', and 'middle_name'. We use each key to generate a neatly formatted full name and email for each user, and then print a summary of what we know about each user.

The screen shot below shows the output of the above program-



Here our discussion about Python dictionary comes to an end. You are advised to practice more by creating some dictionaries as these are widely used in Python projects in real world. So keep learning Python as Python is easy to learn.
Share:

0 comments:

Post a Comment