Reputation:
people = [
{
'name': 'Nate',
'age': 100,
'favorite_color': 'blue',
'salary': 250000.19
},
{
'name': 'George',
'age': 29,
'favorite_color': 'green',
'salary': 59000.50
},
{
'name': 'Wendy',
'age': 63,
'favorite_color': 'red',
'salary': 1000000.64
},
{
'name': 'Amy',
'age': 47,
'favorite_color': 'brown',
'salary': 100000.64
}
]
I want to make an f string that prints the information from the second array in the sentence:
name's salary is <salary> and her favorite color is <favorite_color>
.
I know how to print an f string but I'm having trouble telling the code to pull information from the second array to fill out the information in the sentence. This is what I have so far:
print(f"{name[1]}'s salary is {salary[1]} and her favorite color is {favorite_color[1]}.")
Upvotes: 1
Views: 785
Reputation: 42133
You can use the format() method of strings with values as parameters.
def personInfo(p):
keys = ('name','salary','favorite_color')
sentence = "{}'s salary is {} and her favorite color is {}"
return sentence.format(*map(p.get,keys))
for person in people:
print(personInfo((person)))
Nate's salary is 250000.19 and her favorite color is blue
George's salary is 59000.5 and her favorite color is green
Wendy's salary is 1000000.64 and her favorite color is red
Amy's salary is 100000.64 and her favorite color is brown
To print a specific person (e.g. 2nd one) apply the index to the people
list to get the corresponding dictionary:
print(personInfo(people[1]))
George's salary is 59000.5 and her favorite color is green
Upvotes: 0
Reputation: 475
This would be the correct way to put it:
print(f"{people[1]['name']}'s salary is {people[1]['salary']} and her
favorite color is {people[1]['favorite_color']}.")
Upvotes: 2
Reputation: 102902
for person in people:
print(f"{person['name']}'s salary is {person['salary']} and their favorite color is {person['favorite_color']}.")
This iterates over each entry and lists the fields you're interested in.
Upvotes: 5