【问题标题】:How to split a list of dicts by key如何按键拆分字典列表
【发布时间】:2021-10-26 22:30:49
【问题描述】:

我有以下字典列表:

list_of_dicts = [
    {"type": "X", "hour": 22},
    {"type": "A", "measure": "1"},
    {"type": "B", "measure": "2"},
    {"type": "X", "hour": 23},
    {"type": "A", "measure": "3"},
    {"type": "X", "hour": 24},
    {"type": "A", "measure": "4"},
    {"type": "B", "measure": "5"},
    {"type": "C", "measure": "6"}
]

如何将其拆分为一个 dict,其中键是 'type' = 'X' dicts 中的 'hour' 值,而值是两个 'type' = 'X' dicts 之间的其他 dicts?这就是我想使用这个例子获得的,但是两个 'type' = 'X' dicts 之间的间隔可以是可变的。

dict_of_dicts = {
    22: [
        {"type": "A", "measure": "1"},
        {"type": "B", "measure": "2"},
    ],
    23:[
        {"type": "A", "measure": "3"}
    ],
    24:[
        {"type": "A", "measure": "4"},
        {"type": "B", "measure": "5"},
        {"type": "C", "measure": "6"},
    ]
}

提前致谢!

【问题讨论】:

  • 如果您想手动完成,我建议您尝试用文字描述进行此转换所需的步骤。

标签: python dictionary


【解决方案1】:

这段代码应该可以解决问题。
每次遇到包含“小时”键的字典时,它都会在结果字典中创建新元素。

res = {}
cur_key = None

for d in list_of_dicts:
    if "hour" in d:
        cur_key = d["hour"]
        res[cur_key] = []
    elif cur_key is not None:
        res[cur_key].append(d)

【讨论】:

    【解决方案2】:

    这是另一种使用列表理解和一个​​巧妙的小技巧(借用自 here)的方法来使 while 循环在其中工作:

    list_of_dicts = [
        {"type": "X", "hour": 22},
        {"type": "A", "measure": "1"},
        {"type": "B", "measure": "2"},
        {"type": "X", "hour": 23},
        {"type": "A", "measure": "3"},
        {"type": "X", "hour": 24},
        {"type": "A", "measure": "4"},
        {"type": "B", "measure": "5"},
        {"type": "C", "measure": "6"}
    ]
    
    def while_generator(lst):
        i = 0
        while i < len(lst) and lst[i]['type'] != 'X':
            yield lst[i]
            i += 1
    
    dict_of_dicts = {
        d['hour']: [e for e in while_generator(list_of_dicts[i+1:])]
        for i, d in enumerate(list_of_dicts) if d['type'] == 'X'
    }
    
    print(dict_of_dicts)
    

    打印:

    {
        22: [
            {'type': 'A', 'measure': '1'}, 
            {'type': 'B', 'measure': '2'}
        ], 
        23: [
            {'type': 'A', 'measure': '3'}
        ], 
        24: [
            {'type': 'A', 'measure': '4'}, 
            {'type': 'B', 'measure': '5'}, 
            {'type': 'C', 'measure': '6'}
        ]
    }
    

    【讨论】:

      【解决方案3】:

      跟踪当前的“type X”列表以向其中添加其他字典。

      list_of_dicts = [
          {"type": "X", "hour": 22},
          {"type": "A", "measure": "1"},
          {"type": "B", "measure": "2"},
          {"type": "X", "hour": 23},
          {"type": "A", "measure": "3"},
          {"type": "X", "hour": 24},
          {"type": "A", "measure": "4"},
          {"type": "B", "measure": "5"},
          {"type": "C", "measure": "6"}
      ]
      
      dict_of_dicts = dict()
      for d in list_of_dicts:
          if 'hour' in d: dict_of_dicts[d['hour']] = subList = []
          else:           subList.append(d)
      
      print(dict_of_dicts)
      { 22: [{'type': 'A', 'measure': '1'},
             {'type': 'B', 'measure': '2'}],
        23: [{'type': 'A', 'measure': '3'}],
        24: [{'type': 'A', 'measure': '4'},
             {'type': 'B', 'measure': '5'},
             {'type': 'C', 'measure': '6'}]}
      

      它可以在这样的理解中做到这一点,但它有点令人费解:

      dict_of_dicts = { d['hour']:sl.append([]) or sl[-1]
                        for sl in [[]] for d in list_of_dicts
                        if 'hour' in d or sl[-1].append(d) }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-26
        • 2013-05-22
        • 2010-12-19
        • 2017-04-25
        • 2019-11-20
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多