Home > Software engineering >  How can I count dictionary items with specific values inside list in Python?
How can I count dictionary items with specific values inside list in Python?

Time:05-15

I want to print and count the users who are 'male' and are born on 1973, 1980. Is there a way to search '1973' and '1980' in 'birthday' values so I can count them too?

def getMen():
    count = 0
    users = [
        {'name': 'Bronn', 'gender': 'male', 'birthday': '1973-03-23'},
        {'name': 'Reigar', 'gender': 'male', 'birthday': '1973-11-03'},
        {'name': 'Eiegon', 'gender': 'male', 'birthday': '1963-11-03'},
        {'name': 'Sansa', 'gender': 'female', 'birthday': '2012-11-03'},
        {'name': 'Jon', 'gender': 'male', 'birthday': '1980-11-03'},
        {'name': 'Robb', 'gender': 'male', 'birthday': '1980-05-14'},
        {'name': 'Tisha', 'gender': 'female', 'birthday': '2012-11-03'},
        {'name': 'Rick', 'gender': 'male', 'birthday': '2012-11-03'},
        {'name': 'Joffrey', 'gender': 'male', 'birthday': '1999-11-03'},
        {'name': 'Edd', 'gender': 'male', 'birthday': '1973-11-03'}
    ]

    for user in users:
        if user['gender']=='male':
            count  =1
            print(user)
    print(count)
getMen()

CodePudding user response:

You can extract the year as a substring of the birthday and then compare:

    for user in users:
        if user['gender']=='male' and user['birthday'][0:4] in ['1973', '1980']:
            count  =1
            print(user)

CodePudding user response:

You can filter your list as below and get length of the list to find the count:

count = len(
    [
        user
        for user in users
        if user["gender"] == "male" and user["birthday"].startswith("1973")
    ]
)
  • Related