1

I have a dictionary in Python like this: {'c': 3, 'b': 3, 'aa': 2, 'a': 2}

and I want to print it like this:

b
c
a
aa

I need to sort the dictionary first by the second key and if there are any collisions, sort them lexicographically.

I have searched and can't find any solutions. Here is what I have already tried:

temp = {'c' : 3, 'b': 3, 'aa' : 2, 'a' : 2}
results = []
for key, value in temp.items():
    results.append([key, value])

results.sort(key = operator.itemgetter(1,0), reverse = True)

for result in results:
    print(result)

This doesn't work though it results in this:

c
b
aa
a

The output should be:

b
c
a
aa

I appreciate any help! (Note: using Python 3)

jamiemcg
  • 389
  • 2
  • 7
  • 1
    possible duplicate of [Python sorting list of dictionaries by multiple keys](http://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys) – perror Sep 21 '14 at 10:02

1 Answers1

4
>>> d = {'c': 3, 'b': 3, 'aa': 2, 'a': 2}
>>> sorted(d, key=lambda key: (-d[key], key))
['b', 'c', 'a', 'aa']

- was used to make the value make it ordered descendingly by the value.

falsetru
  • 357,413
  • 63
  • 732
  • 636