-2

I want to get keys of a dictionary, with top 5 values. For example numbers = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6} and I want to get ['one', 'two', 'three', 'four', 'five']

  • `sorted(your_dict.items(), key=lambda item:item[1])[:5]` – keepAlive Dec 14 '17 at 20:20
  • If any answer does what you want, please consider ticking it as correct. A reputation of 1 is enough to do it. I remind you this because newcomers often forget to do so. See [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) That being said, welcome on SO. – keepAlive Dec 14 '17 at 20:25

2 Answers2

0

You can iterate over keys in a dictionary.

myDict = {'one': 1, "two": 2}

for key in myDict:
     print(key)

You could check for the value associated with a key, and add the key to a list if it meets a certain test.

Peritract
  • 761
  • 5
  • 13
0

You can try

r_numbers = {y:x for x,y in numbers.items()}
r_numbers
Out[1]: {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}
[r_numbers[x] for x in sorted(r_numbers.keys())[:5]]
Out[2] : ['one', 'two', 'three', 'four', 'five']
Spandan Brahmbhatt
  • 3,774
  • 6
  • 24
  • 36