Home > Net >  how to get the largest n values in the dictionary but keep the position
how to get the largest n values in the dictionary but keep the position

Time:10-11

The original dictionary is :

{'gfg': 1, 'best': 6, 'geeks': 3, 'for': 7, 'is': 4}

The top N = 3 value pairs are ['for', 'best', 'is'] (sorted by value) but I need ['best', 'for', 'is'] (original dictionary order).

CodePudding user response:

Dictionaries are insertion ordered, but we can't really talk about a position. An acceptable solution could be:

>>> d = {'gfg': 1, 'best': 6, 'geeks': 3, 'for': 7, 'is': 4}
>>> cutoff = sorted(d.values())[-3]
>>> [k for k, v in d.items() if v >= cutoff][:3]
['best', 'for', 'is']
  • Related