A note on the ** basics ** of Python: memo: I'm a Python amateur, so please kindly tell me if there are any mistakes. : penguin:
hashira = [{'Name': 'Yoshiyuki Tomioka', 'Kokyuu': 'water' },
{'Name': 'Butterfly Shinobu', 'Kokyuu': 'Bug' },
{'Name': 'Purgatory Anjuro', 'Kokyuu': 'flame' },
{'Name': 'Umeda Tengen', 'Kokyuu': 'sound' },
{'Name': 'Tokito Muichiro', 'Kokyuu': 'haze' },
{'Name': 'Honeydew Temple Honeydew', 'Kokyuu': 'love' },
{'Name': 'Screaming 嶼 冥', 'Kokyuu': 'rock' },
{'Name': 'Ikuro Kobayashi', 'Kokyuu': 'snake' },
{'Name': 'Immortal river', 'Kokyuu': 'Wind' }]
Get the name of the pillar!
name = [d.get('Name') for d in hashira]
print(name)
# => ['Yoshiyuki Tomioka', 'Butterfly Shinobu', 'Purgatory Anjuro', 'Umeda Tengen', 'Tokito Muichiro', 'Honeydew Temple Honeydew', 'Screaming 嶼 冥', 'Ikuro Kobayashi', 'Immortal river']
If you have a common key, you can get it by value with [key name]
instead of get (key name)
!
kokyuu = [d['Kokyuu'] for d in hashira]
print(kokyuu)
# => ['water', 'Bug', 'flame', 'sound', 'haze', 'love', 'rock', 'snake', 'Wind']
Next are the main characters
kisatsutai = [{'Name': 'Tanjiro Kamado', 'Kokyuu': 'water' },
{'Name': 'Mameko' },
{'Name': 'Inosuke Hashibira', 'Kokyuu': 'beast' },
{'Name': 'Zenitsu Agatsuma', 'Kokyuu': 'Thunder' }]
#Sadako cannot breathe.
Let's get Kokyuu like a pillar.
name = [d.get('Name') for d in kisatsutai]
print(name)
# ['water', None, 'beast', 'Thunder']
As you can see, the get ()
method returns None
by default if the key doesn't exist.
It is also possible to pass the default value in the second argument of get ()
name = [d.get('Name', 'Moo') for d in hashira]
print(name)
# => ['water', 'Moo', 'beast', 'Thunder']
So what if [key name]
instead of get (key name)
?
An error will occur if there is an element that does not have the specified key.
kokyuu = [d['Kokyuu'] for d in kisatsutai]
print(kokyuu)
# => KeyError: 'Kokyuu'
It is also possible to exclude elements that do not have the specified key using the if statement!
name = [d['Kokyuu'] for d in kisatsutai if 'Kokyuu' in d]
print(name)
# => ['water', 'beast', 'Thunder']
As mentioned above, the Python amateur who saw Kimetsu no Yaiba the Movie twice has sent it. => MX/4D was fun.
【reference】 · Get a list of specific key values from a list of dictionaries in Python
Recommended Posts