合并嵌套列表而不影响python中的键和值方向 [英] Combining a nested list without affecting the key and value direction in python
本文介绍了合并嵌套列表而不影响python中的键和值方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个将数据存储在列表中的程序. 当前和所需输出的格式为:
I have a program that stores data in a list. The current and desired output is in the format:
# Current Input
[{'Devices': ['laptops', 'tablets'],
'ParentCategory': ['computers', 'computers']},
{'Devices': ['touch'], 'ParentCategory': ['phones']}]
# Desired Output
[{'Devices': ['laptops', 'tablets','touch'],
'ParentCategory': ['computers', 'computers','phones']}]
您能给我一个关于如何将列表与另一条python代码或逻辑行组合以获得所需输出的想法吗?
Can you give me an idea on how to combine the lists with another python line of code or logic to get the desired output?
推荐答案
您可以执行以下操作:
def convert(a):
d = {}
for x in a:
for key,val in x.items():
if key not in d:
d[key] = []
d[key] += val
return d
上面的代码适用于Python 3.
Code above is for Python 3.
如果您使用的是python 2.7,那么我认为您应该将items
替换为iteritems
.
If you're on Python 2.7, then I believe that you should replace items
with iteritems
.
这篇关于合并嵌套列表而不影响python中的键和值方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文