It's a list comprehension that people who see it for the first time don't understand, but once they start using it, it's a list comprehension, but if you're away from Python for a while, you may forget it, so I made a note of how to use it.
First, simply retrieve your name from the list of profiles.
profiles = [
{"name": "Tanaka", "age": 17},
{"name": "Suzuki", "age": 18},
{"name": "Sato", "age": 19},
]
names = [p["name"] for p in profiles]
print(names)
The result looks like this.
['Tanaka', 'Suzuki', 'Sato']
I will try to put in a bond according to age. Only the names over 18 years old will be taken out.
profiles = [
{"name": "Tanaka", "age": 17},
{"name": "Suzuki", "age": 18},
{"name": "Sato", "age": 19},
]
names = [p["name"] for p in profiles if p["age"] >= 18]
print(names)
Tanaka is excluded because she is under 18 years old.
['Suzuki', 'Sato']
Let's convert the list to a dictionary.
profiles = [
{"name": "Tanaka", "age": 17},
{"name": "Suzuki", "age": 18},
{"name": "Sato", "age": 19},
]
names = {p["name"]: p["age"] for p in profiles}
print(names)
It would be strange if the name was covered, but in this example it's okay.
{'Tanaka': 17, 'Sato': 18, 'Suzuki': 18}
It's a bit brute force, but I'll make a list of names by age.
profiles = [
{"name": "Tanaka", "age": 17},
{"name": "Suzuki", "age": 18},
{"name": "Sato", "age": 18},
]
names = {
p2["age"]: [
p1["name"] for p1 in profiles if p1["age"] == p2["age"]
]
for p2 in profiles}
print(names)
It is like this.
{17: ['Tanaka'], 18: ['Suzuki', 'Sato']}
Recommended Posts