Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional Count in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading