简体   繁体   English

从字典创建字典列表

[英]create a list of dictionaries from a dictionary

I have a dictionary 我有一本字典

d_1 = { 'b':2, 'c':3, 'd':6}

How can I create a list of dictionaries by taking the combinations of the elements of dictionary as dictionary? 如何通过将字典元素的组合作为字典来创建字典列表? Ex: 例如:

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

Use the below loop, in simply get all the numbers from range : [1, 2, 3] , then simply use itertools.combinations and extend to fit them in, also than get the dictionary not with tuple at the end: 使用下面的循环,只需获取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])

You can try this: 您可以尝试以下方法:

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)

Output: 输出:

[{'b': 2}, {'c': 3}, {'d': 6}, {'b': 2, 'c': 3}, {'b': 2, 'd': 6}, {'c': 3, 'd': 6}, {'b': 2, 'c': 3, 'd': 6}]

Using combinations from itertools : 使用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))]

If what you want is a powerset you need to include the empty dictionary, too: 如果您想要的是电源集,则还需要包括空字典:

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

(see itertools recipes ) (请参阅itertools食谱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM