If I have the following:
team = [
{'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
{'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
{'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
{'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]
How can I cound the items in ‘hobbies’ for an person, let’s say Ben. I tried let(), sum(), and some If statements, but none work. Maybe I’m just wrong with the syntax or missing a step. Any help to point me in the right direction?
How would I be able to print the number of hobbies listed for example, for Ben 2, for Sasha 1, etc.
>Solution :
Use len, like so:
team = [
{'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
{'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
{'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
{'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]
for player in team:
print('%s has %d hobbies' % (player['name'], len(player['hobbies'])))
Output:
Ben has 2 hobbies
Quinn has 1 hobbies
Sasha has 1 hobbies
Alex has 0 hobbies