簡體   English   中英

Python將兩個長度不等的字典列表合並為一個基於鍵的列表

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

我將cassandra與python一起使用,並且我正在一起執行兩個查詢。 我想使用列作為鍵將結果的結果分組到一個列表中。

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

我想使用id鍵作為標准將這兩個列表組合在一起

預期結果

[{'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'}]

請提出建議,我該如何以最pythonic的方式執行此操作。 提前致謝。

這是一種方法:

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