![](/img/trans.png)
[英]how to create a dictionary with list of dictionaries as values from a list of dictionaries
[英]create a list of dictionaries from a dictionary
我有一本字典
d_1 = { 'b':2, 'c':3, 'd':6}
如何通過將字典元素的組合作為字典來創建字典列表? 例如:
combs = [{'b':2}, { 'c':3}, {'d':6}, {'b':2, 'c':3}, {'c':3, 'd':6}, {'b':2, 'd':6}, { 'b':2, 'c':3, 'd':6}]
使用下面的循環,只需獲取range
[1, 2, 3]
所有數字,然后只需使用itertools.combinations
進行extend
以適合它們,也可以使字典末尾沒有元組:
ld_1 = [{k:v} for k,v in d_1.items()]
l = []
for i in range(1, len(ld_1) + 1):
l.extend(list(itertools.combinations(ld_1, i)))
print([i[0] for i in l])
您可以嘗試以下方法:
from itertools import chain, combinations
def powerset(iterable):
"""powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(1, len(s) + 1))
d_1 = {'b': 2, 'c': 3, 'd': 6}
comb = list(map(dict, powerset(d_1.items())))
print(comb)
輸出:
[{'b': 2}, {'c': 3}, {'d': 6}, {'b': 2, 'c': 3}, {'b': 2, 'd': 6}, {'c': 3, 'd': 6}, {'b': 2, 'c': 3, 'd': 6}]
使用itertools
combinations
:
[{i:d_1[i] for i in x} for x in chain.from_iterable(combinations(d_1, r) for r in range(1,len(d_1)+1))]
如果您想要的是電源集,則還需要包括空字典:
[{i:d_1[i] for i in x} for x in chain.from_iterable(combinations(d_1, r) for r in range(len(d_1)+1))]
(請參閱itertools食譜 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.