Beginner question.
I have a dictionary as such:
tadas = {'tadas':{'one':True,'two':2}, 'john':{'one':True,'two':True}}
I would like to count the True values where key is 'one'. How should I modify my code?
sum(x == True for y in tadas.values() for x in y.values() )
Access only the one attribute:
sum(item['one'] for item in tadas.values())
This makes use of the fact, that True is equal to 1 and False is equal to 0.
If not every item contains the key 'one' you should use the .get method:
sum(item.get('one', 0) for item in tadas.values())
.get returns the second argument, if the dict does not contain the first argument.
If 'one' can also point to numbers, you should explictly test for is True:
sum(item.get('one', 0) is True for item in tadas.values())
If you dont want to hide the summation in the boolean, you can do it more explicitly with:
sum(1 if item.get('one', False) is True else 0 for item in tadas.values())
List can count occurrences of values, so making use of that is probably most idiomatic:
[x.get('one') for x in tadas.values()].count(True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With