Home > OS >  Count value in dictionary
Count value in dictionary

Time:02-16

I am trying to count the number of times a value is repeated in a dictionary.

Here is my code:

bookLogger = [
    {'BookName': 'Noise', 'Author': 'Daniel Kahneman', 'Process': 'Reading' },
    {'BookName': 'Hunting Party', 'Author': 'Lucy Foley', 'Process': 'Reading'},
    {'BookName': 'Superintelligence', 'Author': 'Nick Bostrom', 'Process': 'Not Reading'}
]

So, I'd want to count 'Reading' for example, so that it prints:

Reading = 2
Not Reading = 1

CodePudding user response:

Keeping it simple, you could do something like this:

reading = 0
notReading = 0

for book in bookLogger:
    if book['Process'] == 'Reading':
        reading  = 1
    elif book['Process'] == 'Not Reading':
        notReading  = 1
        
print(f'Reading: {reading}')
print(f'Not Reading: {notReading}')

Alternatively, you could also use python's list comprehension:

reading = sum(1 for book in bookLogger if book['Process'] == 'Reading')
notReading = sum(1 for book in bookLogger if book['Process'] == 'Not Reading')

print(f'Reading: {reading}')
print(f'Not Reading: {notReading}')

CodePudding user response:

Use collections.Counter to automatize the counting, then a simple loop for displaying the result:

from collections import Counter

# using "get" in case a dictionary has a missing key
c = Counter(d.get('Process') for d in bookLogger) 
# {'Reading': 2, 'Not Reading': 1}

for k,v in c.items():
    print(f'{k} = {v}')

output:

Reading = 2
Not Reading = 1
  • Related