根据列表索引组合字典列表 [英] Combining lists of dictionaries based on list index

查看:242
本文介绍了根据列表索引组合字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这个问题以前必须已经问过,但是在Stack Overflow上找不到.

有没有一种方法可以根据列表索引优雅地组合多个词典列表?见下文:

list_1 = [{'hello': 'world'}, {'foo': 'test'}]
list_2 = [{'a': 'b'}, {'c': 'd'}]
result = [{'hello': 'world', 'a': 'b'},
          {'foo': 'test', 'c': 'd'}]

我了解我可以在技术上使用for循环,例如:

list_3 = []
for i in range(len(list_1)):
    list_3.append({**list_1[i],**list_2[i]})

有没有办法通过列表理解做到这一点? 另外,如果我涉及两个以上的列表,或者不知道词典列表的数量怎么办?

解决方案

这将满足您的要求:

result = [{**x, **y} for x, y in zip(list_1, list_2)]

# [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]

有关**语法的说明,请参见 PEP 448 . /p>

对于通用解决方案:

list_1=[{'hello':'world'},{'foo':'test'}]
list_2=[{'a':'b'},{'c':'d'}]
list_3=[{'e':'f'},{'g':'h'}]

lists = [list_1, list_2, list_3]

def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

result = [merge_dicts(*i) for i in zip(*lists)]

# [{'a': 'b', 'e': 'f', 'hello': 'world'}, {'c': 'd', 'foo': 'test', 'g': 'h'}]

I feel like this question must have been asked previously but could not find it on Stack Overflow.

Is there a way to elegantly combine multiple lists of dictionaries based on list index? See below:

list_1 = [{'hello': 'world'}, {'foo': 'test'}]
list_2 = [{'a': 'b'}, {'c': 'd'}]
result = [{'hello': 'world', 'a': 'b'},
          {'foo': 'test', 'c': 'd'}]

I understand that I can technically use a for loop such as:

list_3 = []
for i in range(len(list_1)):
    list_3.append({**list_1[i],**list_2[i]})

Is there a way to do this with list comprehension? Also what if I have more than 2 lists involved or do not know the number of lists of dictionaries?

解决方案

This will do what you want:

result = [{**x, **y} for x, y in zip(list_1, list_2)]

# [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]

See PEP 448 for an explanation of ** syntax.

For a generalised solution:

list_1=[{'hello':'world'},{'foo':'test'}]
list_2=[{'a':'b'},{'c':'d'}]
list_3=[{'e':'f'},{'g':'h'}]

lists = [list_1, list_2, list_3]

def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

result = [merge_dicts(*i) for i in zip(*lists)]

# [{'a': 'b', 'e': 'f', 'hello': 'world'}, {'c': 'd', 'foo': 'test', 'g': 'h'}]

这篇关于根据列表索引组合字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆