简体   繁体   English

排序多维字典

[英]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)] [(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: @ InsepctorG4dget正确,因为您只反转一个键,而一个键不是(轻松)可逆的-可行的方法是放弃reverse键并反转可逆键:

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: 如果您不介意就地进行稳定排序和修改列表,请使用list.sort两次:

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. 请注意,您的预期输出表明title值在排序时不会反转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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