Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python comprehension loop for dictionary

Tags:

python

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() )
like image 602
tadalendas Avatar asked Dec 19 '22 19:12

tadalendas


2 Answers

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())
like image 109
MaxNoe Avatar answered Dec 21 '22 09:12

MaxNoe


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)
like image 41
Thomas Lotze Avatar answered Dec 21 '22 11:12

Thomas Lotze