values lower than 10 in python dictionary
Question:
hello there I want to get the values in dict
which are lower than number 10
and count them , here is my code.
my code :
counter = 0
dict = {'one': [3, 9, 5, 13], 'two': [6]}
for values in dict :
if dict.values() < 10 :
counter = counter + 1
the output should be like counter = 4
if we print out counter
but i dont how to compare it .
Answers:
An efficient way to do it is a generator comprehension that flattens the nested .values()
of the dictionary and counts them using sum
. It is similar to @matszwecja
‘s comment, but potentially faster because it doesn’t store the values in a list.
my_dict = {'one': [3, 9, 5, 13], 'two': [6]}
counter = sum(1 for values in my_dict.values() for v in values if v < 10)
counter = 0
d_ = {'one':[3,9,5,13], 'two':[6]}
for ki, Lb in d_.items():
for b_ in Lb:
if b_ < 10:
counter += 1
res = []
[res.extend(sub) for sub in dict.values()]
print(len([num for num in res if num < 10]))
hello there I want to get the values in dict
which are lower than number 10
and count them , here is my code.
my code :
counter = 0
dict = {'one': [3, 9, 5, 13], 'two': [6]}
for values in dict :
if dict.values() < 10 :
counter = counter + 1
the output should be like counter = 4
if we print out counter
but i dont how to compare it .
An efficient way to do it is a generator comprehension that flattens the nested .values()
of the dictionary and counts them using sum
. It is similar to @matszwecja
‘s comment, but potentially faster because it doesn’t store the values in a list.
my_dict = {'one': [3, 9, 5, 13], 'two': [6]}
counter = sum(1 for values in my_dict.values() for v in values if v < 10)
counter = 0
d_ = {'one':[3,9,5,13], 'two':[6]}
for ki, Lb in d_.items():
for b_ in Lb:
if b_ < 10:
counter += 1
res = []
[res.extend(sub) for sub in dict.values()]
print(len([num for num in res if num < 10]))