How to improve this program's readability?

72 views Asked by At

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 somewhat like this:

First name: Tu
Last name: Le
Age: 18
City: Hanoi
2

There are 2 answers

0
Sayse On BEST ANSWER

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"
)
0
cao-nv On

I know you got the expected answer, but I still want to give you a small example of how you can control the way to print your data structure, and how to avoid using a certain character repeatly.

class Person:
    def __init__(self, first_name: str, last_name: str, age: int, city: str):
        self.dict = {"first_name": first_name, 
                     "last_name": last_name, 
                     "age": age, 
                     "city": city}
        
    def __str__(self):
        s = "\n".join([f'Fist name: {self.dict["first_name"].title()}',
                       f'Last name: {self.dict["last_name"].title()}',
                       f'Age: {self.dict["age"]}',
                       f'City: {self.dict["city"]}'])
        return s

friend_1 = Person("Hieu", "Tran", 18, "HCMC")

print(friend_1)