简体   繁体   English

如何按字典的值对字典进行排序python

[英]How to sort a dictionary of dictionaries by their values python

I have a user dictionary that looks something like this:我有一个看起来像这样的用户字典:

{
  user1: {
    userLevel: 1,
    userScore: 2
  },
  user2: {
    userLevel: 5,
    userScore: 16
  },
  user3: {
    userLevel: 3,
    userScore: 14
  }
}

and I need to sort it by values, so that the user with the maximum level is 1st, and if some users have the same level then the one with a better score goes 1st.我需要按值对其进行排序,以便具有最高级别的用户为第 1,如果某些用户具有相同的级别,则得分较高的用户为第 1。 If some 2 users have the same level and score, any one of them can go first, it doesn't matter.如果有 2 个用户的等级和分数相同,那么他们中的任何一个都可以先行,没关系。 Is there a clean way to do that?有没有一种干净的方法可以做到这一点?

There are already multiple answer on how to order a dictionnary by values.关于如何按值排序字典已经有多个答案。 The only thing that's changing here is that your items are also dictionnaries.这里唯一改变的是您的项目也是字典。

The fonction sorted allows you to sort a dictionnary on a specific key . sorted功能允许您根据特定键对字典进行排序。

What you're trying to do is to order the dictionnary on a specific key which is in this case the userScore .您要做的是在特定键上订购字典,在本例中为userScore

Therefore you need to find a way to specify that this is the key on which your sortingis based.因此,您需要找到一种方法来指定这是您的排序所基于的键

You also need a way to itterate through your dictionnary .您还需要一种方法来遍历您的字典 This is done with the .items() fonction.这是通过.items()函数完成的。

If your big dictionnary is called a, then a.items() will return a list of tuples where each tuple has a key : user_x and a value : the dictionnary.如果你的大字典被称为 a,那么a.items()将返回一个元组列表,其中每个元组都有一个user_x和一个:字典。

a.items() = [('user1', {'userLevel': 1, 'userScore': 2}), ('user2', {'userLevel': 5, 'userScore': 16}), ('user3', {'userLevel': 3, 'userScore': 14})]

Now you can itterate through these items and you need to specify that for each item that you parse when you iterate, you need to evaluate whether its key userScore is bigger or lower than the others.现在您可以遍历这些项目,并且您需要为您在迭代时解析的每个项目指定,您需要评估其关键 userScore 是大于还是低于其他项。

So for each item x ( a tuple in our case ) they key userScore is retrieved with x[1]['userScore']因此,对于每个项目 x(在我们的例子中是一个元组),它们的 key userScore 是用 x[1]['userScore'] 检索的

The sorting line of code should look something like this :代码的排序行应如下所示:

a = sorted(a.items(), key = lambda tuple : tuple[1]['userScore']

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

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