1

Im trying to sort a dictionary by the values, and i saw this post : Sort a Python dictionary by value

i need to get only the key that have the bigger values in a list,and not in tuple so I wrote this (which look a bit clumsy). BUT if 2 keys had the same value i need to sort them in alphabet way.

this is what i tried to do :

import operator
final_sort=[]
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
for item in sorted_x[::-1]:
    final_sort.append(item[0])

but this is good only for the numbers values condition.

for example :

inp : x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
out : ['c', 'd', 'b', 'a', 'e']
Community
  • 1
  • 1
limitless
  • 669
  • 7
  • 18

2 Answers2

2

Iterating a dictionary yields keys; you can pass the dictionary itself to sorted.

>>> x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
>>> sorted(x, key=lambda key: (-x[key], key))
['c', 'd', 'b', 'a', 'e']
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    This only sorts by value, while the question specifies "BUT if 2 keys had the same value i need to sort them in alphabet way." Since dictionary order is arbitrary, the current `'c', 'd'` is not guaranteed. – TigerhawkT3 Dec 25 '15 at 12:43
  • 2
    @TigerhawkT3, Thank you for comment. I updated the answer accordingly. – falsetru Dec 25 '15 at 13:01
  • Thank you very much. @TigerhawkT3 thank you for the reference, that was exacly what i asked ! anyway thos answer is better for python 3, which didnt let me to unpack tuple like they did it the other post. – limitless Dec 25 '15 at 13:07
0

Here's my take, in 2 steps

>>> x = {'a': 2, 'b': 4, 'c': 6, 'd': 6, 'e': 0}
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 6), ('d', 6), ('b', 4), ('a', 2), ('e', 0)]
>>> [x[0] for x in sorted(x.items(), key=lambda i: i[1], reverse=True)]
['c', 'd', 'b', 'a', 'e']
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • This only sorts by value, while the question specifies "BUT if 2 keys had the same value i need to sort them in alphabet way." Since dictionary order is arbitrary, the current `'c', 'd'` is not guaranteed. – TigerhawkT3 Dec 25 '15 at 12:43