简体   繁体   English

按值对字典排序

[英]Order a dict of dicts by a value

I have a code for the Euros that shows the tables and fixtures etc. With the tables, I have them stored in a json file in a set order that doesn't change, like this:我有一个显示表格和固定装置等的欧元代码。对于表格,我将它们以不变的顺序存储在 json 文件中,如下所示:

    "Table": {
      "Italy": {
        "Played": 0,
        "Won": 0,
        "Draw": 0,
        "Lost": 0,
        "PF": 0,
        "PA": 0,
        "PD": 0,
        "Points": 0
      },
      "Switzerland": {
        "Played": 0,
        "Won": 0,
        "Draw": 0,
        "Lost": 0,
        "PF": 0,
        "PA": 0,
        "PD": 0,
        "Points": 0
      },
      "Turkey": {
        "Played": 0,
        "Won": 0,
        "Draw": 0,
        "Lost": 0,
        "PF": 0,
        "PA": 0,
        "PD": 0,
        "Points": 0
      },
      "Wales": {
        "Played": 0,
        "Won": 0,
        "Draw": 0,
        "Lost": 0,
        "PF": 0,
        "PA": 0,
        "PD": 0,
        "Points": 0
      }
    }

I want to be able to sort the teams by the amount of points they have, or the points difference if the points are the same.我希望能够按他们拥有的积分数量对团队进行排序,或者如果积分相同,则按积分差异对团队进行排序。 Ive looked at Python: sorting dictionary of dictionaries and other related questions and still not been able to figure out how it is possible, any help please?我查看了Python:sorting dictionary of dictionaries和其他相关问题,但仍然无法弄清楚这是怎么可能的,请帮忙?

As said in another thread, you can't sort a dictionary because it is how it works , the workaround here would be to create list of dicts like this, but still, it's pain to work with it and you lose advantages of dictionary正如在另一个线程中所说,您无法对字典进行排序,因为它是它的工作方式,这里的解决方法是创建这样的字典列表,但是使用它仍然很痛苦,并且您失去了字典的优势

table = [
{"Italy": {...}},
{"Switzerland": {...}},
...
{"Wales": {...}},
]

And another workaround will be to create OrderedDict, but it's already explained in the link in your question另一种解决方法是创建 OrderedDict,但它已经在您问题的链接中进行了解释

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

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