SA_Archer
SA_Archer

Reputation: 103

in Python, dictionary sort by value, but only return key

Im using Python 3.3.1 (newbie)

I have a dictionary with a integer key and integer value I need to sort this dictionary and return a list of key where the value falls below a threshold (say 't')

so far I have

list_integer = sorted(dict_int_int.items(), key=lambda x: x[1]  )

this sorts the dictionary by value -- everything is fine so far, but how do I limit the values to be below 't' and then ONLY return the keys

Thanks in Advance

Upvotes: 1

Views: 4075

Answers (3)

marcadian
marcadian

Reputation: 2618

Try this

list_integer = filter(lambda x: x[1] < t, dict_int_int.items()))
list_integer = sorted([x[0] for x in list_integer])

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

try this:

[key for key,value in sorted(dic.items() ,key=lambda x : x[1]) if value < threshold]

or use operator.itemgetter:

>>> from operator import itemgetter
>>> [key for key,value in sorted(dic.items() ,key= itemgetter(1) ) if value < threshold]

Upvotes: 4

abarnert
abarnert

Reputation: 365707

Let's start with what you have:

list_integer = sorted(dict_int_int.items(), key=lambda x: x[1])

This gives you a list of key-value pairs, sorted by values (which makes the name a bit misleading).

Now let's limit the values to be below 't':

list_small = ((k, v) for k, v in list_integer if v < t)

(You could also write that as filter if you prefer.)

And now, let's ONLY return the keys:

list_keys = [k for k, v in list_small]

Of course you can combine any two of these steps, or even combine all three (in which case you end up with Ashwini Chaudhary's answer).


Let's go through these step by step to make sure they work:

>>> dict_int_int = {'a': 1.0, 'b': 0.5, 'c': 0.25, 'd': 0.10 }
>>> t = 0.75
>>> list_integer = sorted(dict_int_int.items(), key=lambda x: x[1])
>>> list_integer
[('d', 0.1), ('c', 0.25), ('b', 0.5), ('a', 1.0)]
>>> list_small = [(k, v) for k, v in list_integer if v < t]
>>> list_small
[('d', 0.1), ('c', 0.25), ('b', 0.5)]
>>> list_keys = [k for k, v in list_small]
>>> list_keys
['d', 'c', 'b']

(Notice that I changed the generator expression list_small into a list comprehension. This is because we need to print out its values, and then use them again. A generator expression only lets you use its values once.)

Upvotes: 0

Related Questions