Kevin
Kevin

Reputation: 597

Python combine items in a dictionary

Suppose

I have A dictionary A

A={'a':{0:[1,2,3],1:[4,5,6]},'b':{0:['u','v','w'],1:['x','y','z']}}

I want to combine all the elements in 'a' and 'b'

that

[[1,2,3,'u','v','w'],
 [1,2,3,'x','y','z'],
 [4,5,6,'u','v','w'],
 [4,5,6,'x','y','z']]

I have tried:

c=[]
for k,v in A.items():
    for i,t in v.items():
        c.append(t+t)

But it does not give the desired result.

Upvotes: 1

Views: 110

Answers (3)

T. Pieper
T. Pieper

Reputation: 36

Just in case someone wants to achieve this for more than two nested dictionaries: The following code works in for those inputs as well:

import itertools

input = {'a':{0:[1,2,3],1:[4,5,6]},'b':{0:['u','v','w'], 1:['x','y','z']}}
list_of_lists = [list(x.values()) for x in input.values()]
res = [list(itertools.chain.from_iterable(x)) for x in itertools.product(*list_of_lists)]
print(res)

Upvotes: 0

sacuL
sacuL

Reputation: 51335

As an alternative to the itertools method outlined above by Ajax1234, you can do it with just list comprehensions:

Start with transforming your dict into a list of lists:

l_of_l = [list(i.values()) for i in A.values()]

Then combine each sublist with another list iteration:

result = [i+v for i in l_of_l[0] for v in l_of_l[1]]

giving you this:

[[1, 2, 3, 'u', 'v', 'w'], [1, 2, 3, 'x', 'y', 'z'], [4, 5, 6, 'u', 'v', 'w'], [4, 5, 6, 'x', 'y', 'z']]

Upvotes: 4

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

import itertools
A={'a':{0:[1,2,3],1:[4,5,6]},'b':{0:['u','v','w'],1:['x','y','z']}}
results = [[c for _, c in b.items()] for a, b in A.items() if a in ['a', 'b']]
last_results = [a+b for a, b in itertools.product(*results)]

Output:

[[1, 2, 3, 'u', 'v', 'w'], [1, 2, 3, 'x', 'y', 'z'], [4, 5, 6, 'u', 'v', 'w'], [4, 5, 6, 'x', 'y', 'z']]

Upvotes: 1

Related Questions