![](/img/trans.png)
[英]List of dictionaries with same structure into single dictionary under single key
[英]single dictionary containing multiple list of lists under the same key. Looking to combining the all values under the same key into a single list
我有一個字典,其中包含一個鍵下的多個列表 - 這是我的字典輸出的一個示例:
print(dic)
輸出:
{1: [[1, 2, 3, 4, 5, 6, 7],
[5, 1, 4, 34, 3, 65, 0, 2],
[2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6],
[2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76],
[6, 11, 16, 17, 38, 62, 66, 77]]}
我希望為每個鍵下的所有列表創建一個列表。 所以我正在尋找的輸出示例如下所示:
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
我嘗試了一個 dict 理解但收效甚微,以及一個我迭代 dic.items() 的 for 循環。
您可以使用字典理解:
{key: [[item for sublist in value for item in sublist]] for key, value in data.items()}
這輸出:
{
1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]
}
嘗試使用itertools.chain.from_iterable
:
>>> import itertools
>>> {k : [list(itertools.chain.from_iterable(v))] for k,v in dct.items()}
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
使用itertools.chain
:
from itertools import chain
out = {k: [list(chain.from_iterable(l))]
for k,l in dic.items()}
輸出:
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.