I want to use data from a list of dictionaries in a string. For example
dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
print(f"His name is {??} and he is {??} years old")
I need to know what to replace the question marks with to make it work.
I have looked a lot of stack overflow and found some things, but nothing to get one specific item. I found
print([item["name"]for item in dict])
CodePudding user response:
Iterate over the dicts, and then use the []
operator to get the name
and age
keys.
people = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
for p in people:
print(f"Their name is {p['name']} and they are {p['age']} years old")
Their name is Matt and they are 21 years old
Their name is Sally and they are 28 years old
CodePudding user response:
- For print all persons in the
dict
:
for person in dict:
print(f"His name is {person['name']} and he is {person['age']} years old")
output:
His name is Matt and he is 21 years old
His name is Sally and he is 28 years old
- For print one person in the
dict
, using his index (index1
in this example):
print(f"His name is {dict[1]['name']} and he is {dict[1]['age']} years old")
output:
His name is Sally and he is 28 years old
CodePudding user response:
dict = [{'name':'Matt', 'age':'21'},{'name':'Sally','age':'28'}]
dict
is a list of dictionaries. (Terrible variable name choice, by the way. dict
is already the name of something built-in to Python, so by using that as a variable name, you've lost its original meaning. Plus, you're using dict
to hold a list of people, so the name itself is not very meaningful. people
would be a much better name.)
Lists are accessed by an integer index. So in this case, dict[0]
is Matt's entry, and dict[1]
is Sally's entry.
Now that you know dict[0]
is Matt's entry, you can use the standard dictionary key syntax.
Matt's name is dict[0]['name']
and his age is dict[0]['age']
.
Likewise Sally's name is dict[1]['name']
and her age is dict[1]['age']
.
(All of this is very basic Python syntax. What part, exactly, did you have trouble with?)