Finding the length of keys of dictionary based on values

Question:

input_dict = {'ab':12, 'cd':4, 'ef':1, 'gh':8, 'kl':9}
out_dict = 2

Is there any way to find the length of keys of the dictionary, if the values in dictionary are greater than 2 and less than 9?

Asked By: Noorulain Islam

||

Answers:

I think you want to find number of items in dictionary where value is 2 < v < 9:

input_dict = {"ab": 12, "cd": 4, "ef": 1, "gh": 8, "kl": 9}

out = sum(2 < v < 9 for v in input_dict.values())
print(out)

Prints:

2
Answered By: Andrej Kesely

Try this,

In [61]: len([v for v in d.values() if 2 < v < 9])
Out[61]: 2
Answered By: Rahul K P

Just returning the relevant lengths:

[len(k) for k, v in input_dict.items() if 2 < v < 9]

Returns:

[2, 2]
Answered By: Roland Smith
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.