Python comprehension loop for dictionary

Beginner Question.

I have a dictionary as such:

tadas = {'tadas':{'one':True,'two':2}, 'john':{'one':True,'two':True}}

I would like to count True Values, where the key is "one." How do I change the code?

sum(x == True for y in tadas.values() for x in y.values() )
+4
source share
4 answers

Access to only one attribute:

sum(item['one'] for item in tadas.values())

It takes advantage of the fact that Trueequal 1, but Falseequal 0.

If not every element contains a key 'one', you should use the method .get:

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'it can also point to numbers, you should explicitly test is True:

sum(item.get('one', 0) is True for item in tadas.values())

If you do not want to hide the summation in the logical, you can do this more explicitly with:

sum(1 if item.get('one', False) is True else 0 for item in tadas.values())
+6

, , , :

[x.get('one') for x in tadas.values()].count(True)
+3

:

print(sum(1 for x in tadas.values() if x['one']))

. , , , .

+1

You can use a filter to filter the list of any values ​​where "one" does not match True. Then just return the length of the list.

len(filter(lambda x: tadas[x]['one'], tadas))
+1
source

Source: https://habr.com/ru/post/1629932/