Python combine items in a dictionary

走远了吗. 提交于 2020-03-25 04:05:03

问题


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.


回答1:


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



回答2:


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



回答3:


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)


来源:https://stackoverflow.com/questions/49183510/python-combine-items-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!