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
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 sep
arator 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"
)