naive
naive

Reputation: 367

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

Upvotes: 1

Views: 254

Answers (3)

user2314737
user2314737

Reputation: 29307

Using combinations from 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))]

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)

Upvotes: 2

DDGG
DDGG

Reputation: 1241

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

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71570

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:

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

Upvotes: 4

Related Questions