【问题标题】:How to simplify a dictionary of nested lists in python?如何简化python中嵌套列表的字典?
【发布时间】:2016-04-16 23:19:57
【问题描述】:

我目前有这本带有嵌套列表的字典:

dict_with_nested_list = {
    'B': [['a', 2], ['b', 4]],
    'A': [['a', 1], ['b', 3]]
}

correct_order = ['A', 'B']

我正在尝试简化它,以便每个嵌套列表的顺序正确,其元素是键及其对应的值:

desired_output = [
    ['a', 1, 2],
    ['b', 3, 4]
]

【问题讨论】:

    标签: python list dictionary list-comprehension


    【解决方案1】:
    from collections import OrderedDict
    
    ret = OrderedDict()
    for order in correct_order:
        for key, value in dict_with_nested_list[order]:
            if key not in ret:
                ret[key] = []
            ret[key].append(value)
    
    print [[key] + value for key, value in ret.items()]
    

    【讨论】:

      【解决方案2】:

      我强烈建议保留某种字典结构,每个值都有一个list。如果需要,您可以稍后将其转换为另一种结构。

      >>> import collections
      >>> dict_with_nested_list = {
      ...     'B': [['a', 2], ['b', 4]],
      ...     'A': [['a', 1], ['b', 3]]
      ... }
      >>> result = collections.defaultdict(list)
      >>> for l in dict_with_nested_list.values():
      ...     for k,v in l:
      ...             result[k].append(v)
      ...
      >>> result = {k:sorted(v) for k,v in result.items()}
      >>> result
      {'b': [3, 4], 'a': [1, 2]}
      >>> sorted(result.items())
      [('a', [1, 2]), ('b', [3, 4])]
      >>> [[k]+v for k,v in sorted(result.items())]
      [['a', 1, 2], ['b', 3, 4]]
      

      【讨论】:

        【解决方案3】:

        你可以像这样把它变成一本合理的字典

        from collections import defaultdict
        
        dict_output = defaultdict(list)
        for key, list_of_pairs in sorted(dict_with_nested_list.items()):
            for lowerkey, value in list_of_pairs:
                dict_output[lowerkey].append(value)
        
        print(dict(dict_output))
        

        这会导致这个字典:

        {'a': [1, 2], 'b': [3, 4]}
        

        你可以像这样将该字典转换成你想要的输出:

        desired_output = [[key] + values for key, values in sorted(dict_output.items())]
        
        print(desired_output)
        

        结果

        [['a', 1, 2], ['b', 3, 4]]
        

        【讨论】:

          猜你喜欢
          • 2023-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-04
          • 2021-05-10
          • 2016-06-09
          • 1970-01-01
          相关资源
          最近更新 更多