[英]How to split a list of dicts by key
我有以下字典列表:
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"}
]
我怎樣才能把它分成一個字典,其中鍵是來自 'type' = 'X' 字典的 'hour' 值,而值是兩個 'type' = 'X' 字典之間的其他字典? 這就是我想使用這個例子獲得的,但是兩個 '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"},
]
}
提前致謝!
這段代碼應該可以解決問題。
每次遇到包含“小時”鍵的字典時,它都會在結果字典中創建新元素。
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)
這是另一種使用列表理解的方法和一個巧妙的小技巧(從這里借來的)在其中創建一個 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'}
]
}
跟蹤當前的“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) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.