从字典创建字典列表

时间:2019-04-17 06:32:55

标签: python 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}]

3 个答案:

答案 0 :(得分:3)

使用下面的循环,简单地从range中获取所有数字:[1, 2, 3],然后简单地使用itertools.combinationsextend来使它们适合,而不是得到字典末尾没有元组:

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 :(得分:1)

您可以尝试以下方法:

> plot_grid(plotlist = genes.cluster2.alpha))

输出:

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)

答案 2 :(得分:1)

使用combinations中的itertools

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

如果您想要的是 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 recipes