【发布时间】:2020-02-14 19:16:41
【问题描述】:
我有三个 python 列表,我想将它们制作成一个字典,然后根据键值将这三个字典连接到一个字典中。
我的 python 列表是这样制作的:
with open ('full_product_shipments.xml','r') as file2:
full_product_shipments = list([line.strip().replace('{"','').replace('}','').replace('"','').replace(':',',').split(',') for line in file2])
它们看起来像这样:
列表1
[['transaction_id', '224847627', 'product_amount', '2.73', 'user_invoice_date', '2018-12-21'],
['transaction_id', '67919397', 'product_amount', '2.73', 'user_invoice_date', '2017-10-26']]
list2
[['tracking_code', '29285908', 'from_country', 'FR', 'to_country', 'FR', 'package_type_id', '10', 'transaction_id', '172238850', 'shipping_label_created', '2018-09-25 18', '40', '52'],
['tracking_code', '22105784', 'from_country', 'FR', 'to_country', 'FR', 'package_type_id', '10', 'transaction_id', '111423825', 'shipping_label_created', '2018-04-13 11', '22', '44']]
列表3
[['tracking_code', '21703238', 'from_country', 'FR', 'to_country', 'FR', 'amount', '3.23'],
['tracking_code', '41545695', 'from_country', 'FR', 'to_country', 'FR', 'amount', '2.9']]
list1 和 list2 都有transaction_id,一旦我将它们转换为字典,我就需要加入它们。
新加入的列表(list1和list2)和list3都有tracking_id,我想通过它加入他们一次list3 被转换为字典。
我试过用这个:
result=[x.update(amount=y['amount']) for x in full_product_shipments for y in full_provider_invoices if x['transaction_id'] == y['transaction_id']]
但这会引发 TypeError:
TypeError: list indices must be integers or slices, not str
也许没有必要将所有内容都转换为 dict。我是 python 的新手,所以如果有更好的方法来基于键合并信息,我将不胜感激。
【问题讨论】:
-
full_product_shipments、full_provider_invoices等是哪个列表? -
第一个列表是
full_product_invoices,第二个列表是full_product_shipments,第三个列表是full_provider_invoices。
标签: python list dictionary merge