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

How to improve this program's readability?

I’m learning the basic of Python dictionaries and am having an exercise on nesting dictionaries in a list. It basically told me to make 3 dictionaries about 3 people, nest them inside a list, loop through the list, and print out the info of each person.
I have already had the output I wanted, but my print statement was hard to read with a lot of \n. Can you suggest other ways to improve readability?

My code:

friend_1 = {
    "first_name": "Tu",
    "last_name": "Le",
    "age": 18,
    "city": "Hanoi"
}

friend_2 = {
    "first_name": "Hao",
    "last_name": "Do",
    "age": 18,
    "city": "Hanoi"
}

friend_3 = {
    "first_name": "Hieu",
    "last_name": "Tran",
    "age": 18,
    "city": "HCMC"
}

friends = [friend_1, friend_2, friend_3]

for friend in friends:
    print(f"\nFirst name: {friend['first_name'].title()}\nLast name: {friend['last_name'].title()}\nAge: {friend['age']}\nCity: {friend['city'].title()}")

The output looks like this (I only captured 1/3 of it):

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

>Solution :

Assuming the problem is the way it appears in the print statement, you can make use of the fact print can take in lots of arguments to print and then specify a separator that can be used to define how to separate all the individual elements you’ve included in the print statement

print(
     f"First name: {friend['first_name'].title()}",
     f"Last name: {friend['last_name'].title()}",
     f"Age: {friend['age']}",
     f"City: {friend['city'].title()}",
     sep="\n"
)
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