首页 > 解决方案 > 从字典创建字典列表

问题描述

我有一本字典

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

标签: pythondictionary

解决方案


使用下面的循环,简单地从range:中获取所有数字[1, 2, 3],然后简单地使用itertools.combinationsandextend来适应它们,而不是在最后获取字典而不是元组:

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

推荐阅读