【问题标题】:Sorting multiple dictionary dimensions at once一次对多个字典维度进行排序
【发布时间】:2017-08-20 11:42:16
【问题描述】:

我有一本如下形式的字典:

{
    "b":{
          "ba": {
                 "Score":3,
                 "N":500
                },
          "aa": {
                 "Score": 10,
                 "N":300
                },
        },
    "a":{
         "xy": {
                 "Score":199,
                 "N":7
               },
         "zz": {
                 "Score":222,
                 "N":55
               },
         }
}

我希望第一个维度按字母顺序排序,而第二个维度按Score 排序,这样排序后看起来像:

{
    "a":{
         "zz": {
                 "Score":222,
                 "N":55
               },
         "xy": {
                 "Score":199,
                 "N":7
               }
         },
    "b":{
          "aa": {
                 "Score": 10,
                 "N":300
                },
          "ba": {
                 "Score":3,
                 "N":500
                }
        }
}

我已经搜索了一段时间的答案,但我只找到了如何对字典中的单个维度进行排序。最好的 Pythonic 方法是什么?

排序后,我需要将其转储到我计划使用json 模块的文件中。所以做类似的事情:

with open("out.json", 'w') as fp:
    json.dump(my_dict, fp, sort_keys=True, indent=4)

【问题讨论】:

  • 只是一个小障碍:字典是无序的。
  • @MSeifert 我知道字典在 Python 中存储时是无序的,但我需要按照我的编辑将其排序(如所述)输出到 json 文件中。
  • 那么使用OrderedDict 就可以了吗?
  • 构建一个包含其他有序字典的有序字典并将它们转储为 json。

标签: python python-3.x sorting dictionary


【解决方案1】:

您可以使用以下示例创建适当的OrderedDict

ordered = OrderedDict(
    [(k, OrderedDict(
        sorted(v.items(), key=lambda pair: -pair[1]["Score"]))) 
     for k, v in sorted(data.items())])

现在转储到 json

>>> print(json.dumps(ordered, indent=2))
{
  "a": {
    "zz": {
      "Score": 222, 
      "N": 55
    }, 
    "xy": {
      "Score": 199, 
      "N": 7
    }
  }, 
  "b": {
    "aa": {
      "Score": 10, 
      "N": 300
    }, 
    "ba": {
      "Score": 3, 
      "N": 500
    }
  }
}

注意:您可以在内部排序中使用 reverse=True 而不是否定分数,这取决于您的感受...

【讨论】:

    【解决方案2】:

    您必须使用OrderedDict,因为普通字典是无序的,因此将排序后的字典放在另一个普通字典中会再次丢弃该顺序。

    然后先对外键排序,再对内字典就地排序:

    from collections import OrderedDict
    
    d = {"b":{"ba": {"Score":3, "N":500},
              "aa": {"Score": 10, "N":300},},
        "a":{"xy": {"Score":199, "N":7},
             "zz": {"Score":222, "N":55},}}
    
    d = OrderedDict(sorted(d.items()))  # sorts the outer keys
    for k, v in d.items():
        # sort the inner keys by score
        d[k] = OrderedDict(sorted(v.items(), key=lambda x: x[1]['Score'], reverse=True))
    

    之后d 看起来像这样:

    OrderedDict([('a',
                  OrderedDict([('zz', {'N': 55, 'Score': 222}),
                               ('xy', {'N': 7, 'Score': 199})])),
                 ('b',
                  OrderedDict([('aa', {'N': 300, 'Score': 10}),
                               ('ba', {'N': 500, 'Score': 3})]))])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-22
      • 2016-03-14
      • 2021-12-21
      • 2012-07-29
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多