简体   繁体   English

Python将两个长度不等的字典列表合并为一个基于键的列表

[英]Python combine two lists of dictionaries of unequal lengths into a single list based on a key

I am using cassandra with python and i am executing two queries together. 我将cassandra与python一起使用,并且我正在一起执行两个查询。 I want to group the results of the results together into a single list using a column as key. 我想使用列作为键将结果的结果分组到一个列表中。

list1 = [{'firstname':'foo','lastname':'bar','id':1},{'firstname':'foo2','lastname':'bar2','id':2}]
list2 = [{'text':'sample','contact_no':'666','id':1},{'text':'sample2','contact_no':'111','id':1}, {'text':'sample3','contact_no':'121','id':2}]

I want to group these two lists together using id key as the criteria 我想使用id键作为标准将这两个列表组合在一起

Expected result 预期结果

[{'firstname':'foo','lastname':'bar','id':1,'text':'sample','contact_no':'666'}, {'firstname':'foo','lastname':'bar','id':1,'text':'sample2','contact_no':'111'},{'firstname':'foo2','lastname':'bar2','id':2,'text':'sample3','contact_no':'121'}]

Please advice on how can i do this the most pythonic way. 请提出建议,我该如何以最pythonic的方式执行此操作。 Thanks in advance. 提前致谢。

This is one way: 这是一种方法:

import itertools

list1 = [{'firstname':'foo','lastname':'bar','id':1},
         {'firstname':'foo2','lastname':'bar2','id':2}]
list2 = [{'text':'sample','contact_no':'666','id':1}, 
         {'text':'sample2','contact_no':'111','id':1}, 
         {'text':'sample3','contact_no':'121','id':2}]

lst = []
for x, y in itertools.product(list1, list2):
    if x['id'] == y['id']:
        c = x.copy()
        c.update(y)
        lst.append(c)

print(lst)
# [{'firstname': 'foo', 'lastname': 'bar', 'id': 1, 'text': 'sample', 'contact_no': '666'}, 
#  {'firstname': 'foo', 'lastname': 'bar', 'id': 1, 'text': 'sample2', 'contact_no': '111'}, 
#  {'firstname': 'foo2', 'lastname': 'bar2', 'id': 2, 'text': 'sample3', 'contact_no': '121'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM