Search code examples
pythonlistdictionarylist-comprehensiondictionary-comprehension

Comprehension on Sorting through a dictionary and returning the key for a certain amount of values above a threshold


I've figured my comprehension and gotten it to work for returning the keys of a sorted list. So i'm currently returning the first X amount of keys with the lowest values. I'm not exactly sure how to place a stipulation on this of having the values above a threshold.

coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
x = -3.5
main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True)[:2]])

I'm not sure how eactly to fit it in this, but i want it to take the 2 values that are above the threshold (x). I've seen where the >= x is after the dict.items(), but that doesn't seem to work for me.

main_list = ([i[0] for i in sorted(coin_loss_dict.items() >= x, key=lambda x:x[1], reverse=True)[:2]])

I get a nice error that tells me that i can't do that between instances of dict_items and float.

TypeError: '>=' not supported between instances of 'dict_items' and 'float'

I'd appreciate any help i can get. I know the comprehension isn't the most beautiful to work with, but it works for what i need with the exception of the threshold which i can't seem to incorporate.


Solution

  • Try this:

    coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
    x = -3.5
    main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True) if i[1] >= x])