简体   繁体   中英

Sort Multi-dimensional dictionary

I have a dictionary in the format given below. I want to sort the dictionary based on the value of the "score" values in decreasing order, and in case of a tie, sort in lexicographical order of the "title" value.

d = {
   '123':{
        'score': 100,
        'title': 'xyz'
    },
   '234':{
        'score': 50,
        'title': 'abcd'
    },
    '567':{
        'score': 50,
        'title': 'aaa'
    }
}

So the output should be:

[(100,xyz), (50,aaa), (50,abcd)]

I have tried this:

  print sorted(d.items(), key=lambda x: (x[1]['score'], x[1]['title']), reverse=True)

But it is sorting in decreasing order for both fields.

@InsepctorG4dget has it right, since you're only reversing one key, and one key is not (easily) reversible - the way to go is dropping the reverse and reversing the reversible key:

items = sorted(
    d.items(),
    # note -x[1]['score'] is negated value
    key=lambda x: (-x[1]['score'], x[1]['title'])
)

If you don't mind stable-sorting in-place and modifying a list use list.sort twice:

items = d.items()
# last key first
items.sort(key=lambda x: x[1]['title'])
# first key last
items.sort(key=lambda x: x[1]['score'], reverse=True)

Result:

>>> items
[('123', {'score': 100, 'title': 'xyz'}), ('567', {'score': 50, 'title': 'aaa'}), ('234', {'score': 50, 'title': 'abcd'})]

>>> [(x[1]['score'], x[1]['title']) for x in items]
[(100, 'xyz'), (50, 'aaa'), (50, 'abcd')]

Note that your expected output suggests title values are not reversed when sorted.

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