Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there way to print-format this dictionary in a more presentable way?

product_dict = {"Jeans": 150, "Jacket": 300, "Perfume": 50, "Wallet": 125, "Glasses": 100}
#product dictonary with prices    
order_history = {'Andrew':[{'Jeans':2, 'Wallet': 4}, {'Perfume':2}], 'Max':[{'Jacket': 3}]}
c_name = input('customer name: ')
print('The following is order history of, c_name')
key = order_history['c_name']
for i in range(len(key)):
    print('purchase', i+1, key[i])

I am creating a retail check out program, I have a predefined products stored in a dictionary along with prices that I use in other part of program, I wanted to print the output in a more presentable like this:

This is the order history of Andrew.
            Jeans Wallet Perfume Jacket
Purchase 1:  2       4
Purchase 2:                 2

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use a nested loop to print the quantity of each item, by looping over the keys of product_dict. Use end='' to print all the quantities on the same line, and use fixed-width fields in the formatting string to make everything line up.

product_dict = {"Jeans": 150, "Jacket": 300, "Perfume": 50, "Wallet": 125, "Glasses": 100}
#product dictonary with prices
order_history = {'Andrew':[{'Jeans':2, 'Wallet': 4}, {'Perfume':2}], 'Max':[{'Jacket': 3}]}
c_name = 'Andrew'

print(f'The following is order history of {c_name}')
print(' ' * 12, end='')
for product in product_dict:
    print(f'{product:10}', end='')
print()
key = order_history[c_name]
for i, items in enumerate(key, 1):
    print(f'Purchase {i}:  ', end='')
    for product in product_dict:
        if product in items:
            print(f'{items[product]:<10}', end='')
        else:
            print(' ' * 10, end='')
    print()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading