-5

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
Abdullah Khawer
  • 4,461
  • 4
  • 29
  • 66
  • 3
    What have you tried? (Show properly formatted code in the question). – Michael Butscher Feb 15 '22 at 12:52
  • 1
    `sum(1 for x in bookLogger if x['Process'] == 'Reading')` – kabanus Feb 15 '22 at 12:55
  • @kabanus This works thank you. I get the code from `for x onwards` but what does the `sum(1` part mean? I am assuming it means to count the amount of times its repeated? –  Feb 15 '22 at 13:00
  • Does this answer your question? [Most pythonic way of counting matching elements in something iterable](https://stackoverflow.com/questions/157039/most-pythonic-way-of-counting-matching-elements-in-something-iterable) – tevemadar Feb 15 '22 at 13:06
  • Also https://stackoverflow.com/questions/35421378/get-count-of-repeated-values-in-a-list-of-dictionary – tevemadar Feb 15 '22 at 13:07

2 Answers2

1

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}')
Eleasar
  • 126
  • 1
  • 4
0

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
mozway
  • 194,879
  • 13
  • 39
  • 75