Printing nested dictionary

Question:

I have 2 dictionaries:

movie_collections_dict = {'Avatar':0, 'Titanic':0, 'StarWar':0}
#which indicates the revenues of the movies

and

{'avatar': {'adult': 0,
            'child': 0,
            'concession': 0,
            'senior': 0,
            'student': 0},
 'starwar': {'adult': 0,
             'child': 0,
             'concession': 0,
             'senior': 0,
             'student': 0},
 'titanic': {'adult': 0,
             'child': 0,
             'concession': 0,
             'senior': 0,
             'student': 0}}
#which shows that this much seats are booked for a particular ticket type for a movie

I want to print the dictionaries in such a way that it will be shown as:

         adult  child  student  senior  concession  Revenue
Avatar       0      0        0       0           0        0
Titanic      0      0        0       0           0        0
StarWar      0      0        0       0           0        0

I don’t want to use any external modules such as pandas or anything.

Asked By: Mukund Panchal

||

Answers:

One way is you can use .format().

Code:

movie_collections_dict = {'Avatar': 0, 'Titanic': 0, 'StarWar': 0}
tickets_dict = {'avatar': {'adult': 0, 'child': 0, 'student': 0, 'senior': 0, 'concession': 0},
                'starwar': {'adult': 0, 'child': 0, 'student': 0, 'senior': 0, 'concession': 0},
                'titanic': {'adult': 0, 'child': 0, 'student': 0, 'senior': 0, 'concession': 0}}

print("{:<11}{:<10}{:<10}{:<10}{:<12}{:<12}{:<10}".format(' ', 'adult', 'child', 'student', 'senior', 'concession', 'Revenue'))

for movie_name, revenue in movie_collections_dict.items():
    adult_sales = tickets_dict[movie_name.lower()]['adult']
    child_sales = tickets_dict[movie_name.lower()]['child']
    student_sales = tickets_dict[movie_name.lower()]['student']
    senior_sales = tickets_dict[movie_name.lower()]['senior']
    concession_sales = tickets_dict[movie_name.lower()]['concession']
    print("{:<11}{:<10}{:<10}{:<10}{:<12}{:<12}{:<10}".format(movie_name, adult_sales, child_sales, student_sales, senior_sales, concession_sales, revenue))

{:<10} means left aligned and 10 defines minimum width be taken. i.e(10 characters) you can change as per your need. you should take padding atleast greater than the max character of the word.

Output:

           adult     child     student   senior      concession  Revenue   
Avatar     0         0         0         0           0           0         
Titanic    0         0         0         0           0           0         
StarWar    0         0         0         0           0           0
Answered By: Yash Mehta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.