简体   繁体   中英

How to sort a dictionary by values which are lists using itemgetter?

I have the following dictionary:

Dict = {'1': ['Adam', 27], '2': ['Brad', 31], '3': ['Paul', 19]}

I would like to sort it by the int value in the list in ascending order. So my desired result is:

Desired = {'3': ['Paul', 19], '1': ['Adam', 27], '2': ['Brad', 31]}

I'm trying to execute the following:

v = sorted(Dict.items(), key=operator.itemgetter([1][1]))

But it keeps on erroring out with:

v = sorted(Dict.items(), key=operator.itemgetter([1][1]))
IndexError: list index out of range

Can I not pass the item using multiple dimensions to itemgetter? What am I missing?

Thanks!

You can't use itemgetter here in this case. Use lambda :

>>> sorted(Dict.items(), key=lambda x: x[1][1])
[('3', ['Paul', 19]), ('1', ['Adam', 27]), ('2', ['Brad', 31])]

Create my own function where I pass the value from the dictionary

You can but you have to use Dict.items() :

def my_sort(x):
    return x[1][1]

sorted(Dict.items(), key=my_sort)
# [('3', ['Paul', 19]), ('1', ['Adam', 27]), ('2', ['Brad', 31])]

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