【问题标题】:Sort nested dictionary across multiple keys跨多个键对嵌套字典进行排序
【发布时间】:2018-10-21 14:02:31
【问题描述】:

我希望所有字典值都按升序排列。

我的字典 df 如下所示:

df = {("A",): {"a": {"a1": 0.5, "a2": 0.2, "a3":1.0}},
      ("B",): {"b1": 0.8, "b2": 0.4}}

我的理想输出是:

A⇨
 a→a2:0.2
B⇨
 b2→0.4
A⇨
 a→a1:0.5
  ・
  ・
  ・

这是我写的:

for key,value in sorted(df.items(), key=lambda x:x[0]):
    print(key)
    print(value)

但是当我运行它时,字典是按字母顺序排序的……像key=lambda x:x[1]这样重写会引发KeyError

我该怎么做?

【问题讨论】:

  • 所以你想跨多个键排序?
  • @Ev.Kounis yes,ido
  • 你确定df 像你展示的那样,而不像df = {("A",): {"a": {"a1": 0.5, "a2": 0.2, "a3":1.0}}, ("B",): {"b1": 0.8, "b2": 0.4}}("B", ) 是否包含在 ("A", ) 中?
  • @Ev.Kounis 你是对的,df 是 df = {("A",): {"a": {"a1": 0.5, "a2": 0.2, "a3":1.0}}, ("B",): {"b1": 0.8, "b2": 0.4}} 我正在编辑我的信息

标签: python sorting dictionary nested


【解决方案1】:

我首先将dict 展平,然后对其进行排序。比如:

def flatten_dict(d_in, d_out, parent_key):
    for k, v in d_in.items():
        if isinstance(v, dict):
            flatten_dict(v, d_out, parent_key + (k,))
        else:
            d_out[parent_key + (k,)] = v


df = {("A",): {"a": {"a1": 0.5, "a2": 0.2, "a3":1.0}},
    ("B",): {"b1": 0.8, "b2": 0.4}}

d_out = {}

flatten_dict(df, d_out, tuple())

print(d_out)

for key, value in sorted(d_out.items(), key=lambda x: x[1]):
    print(key)
    print(value)

这样,您仍然可以使用它通过扁平键查找值。

【讨论】:

    【解决方案2】:

    一种解决方案是使用递归函数将字典转换为元组列表,例如:

     (('A',), 'a', 'a1', 0.5), (('A',), 'a', 'a2', 0.2), (('A',), 'a', 'a3', 1.0), ...
    

    然后对这个元组列表进行排序:

    def dict_to_list(input_dict):
        for key, value in input_dict.items():
            if isinstance(value, dict):
                for nested_value in dict_to_list(value):
                    yield (key, ) + nested_value
            else:
                yield (key, value)
    
    print(sorted(dict_to_list(df), key=lambda value: value[-1]))
    
    
    >>> [(('A',), 'a', 'a2', 0.2), (('B',), 'b2', 0.4), (('A',), 'a', 'a1', 0.5), (('B',), 'b1', 0.8), (('A',), 'a', 'a3', 1.0)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2018-07-03
      • 1970-01-01
      • 2021-05-17
      • 2019-02-08
      相关资源
      最近更新 更多