Python 从字典创建字典列表

Python 从字典创建字典列表,python,dictionary,Python,Dictionary,我有一本字典 d_1 = { 'b':2, 'c':3, 'd':6} 如何将dictionary元素的组合作为dictionary来创建dictionary列表?例: 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}] 使用下面的循环,简单地获取范围:[1,2,3]中的所有数字,然后简单地使用itertools.combine

我有一本字典

d_1 = { 'b':2, 'c':3, 'd':6}
如何将dictionary元素的组合作为dictionary来创建dictionary列表?例:

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}]

使用下面的循环,简单地获取范围:[1,2,3]中的所有数字,然后简单地使用itertools.combines并进行扩展以适应它们,而不是获取末尾不带元组的字典:

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])

使用下面的循环,简单地获取范围:[1,2,3]中的所有数字,然后简单地使用itertools.combines并进行扩展以适应它们,而不是获取末尾不带元组的字典:

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}]
您可以尝试以下方法:

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中的组合:

如果您想要的是powerset,则还需要包括空字典:

[{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中的组合:

如果您想要的是powerset,则还需要包括空字典:

[{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))]