简体   繁体   中英

Sorting a Dictionary in Python by two keys (frequency and lexicographically)

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)

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM