gpt4 book ai didi

python - 我如何遍历字典列表并合并字典以形成新的更短的字典列表?

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:26 24 4
gpt4 key购买 nike

我有一个包含'price''tickettype' 的航空公司航类票价列表,指示票价是否为“单程”(相对于往返并通过整数代码映射到另一个旅程列表。但我收到的列表是重复的。

[
{'price' : 1800, 'oneway' : 1, 'inboundJourneys' : [], "outboundJourneys": [3], 'tickettypecode' : 'SDS'},
{'price' : 1800, 'oneway' : 1, 'inboundJourneys' : [9,10,11], "outboundJourneys": [], 'tickettypecode' : 'SDS'},
{'price' : 1800, 'oneway' : 1, 'inboundJourneys' : [14,16], "outboundJourneys": [], 'tickettypecode' : 'SDS'},
{'price' : '2300', 'oneway' : 1, 'inboundJourneys' : [], "outboundJourneys": [6,8,9], 'tickettypecode' : 'TAR'},
{'price' : 2300, 'oneway' : 1, 'inboundJourneys' : [12,13,14], "outboundJourneys": [3], 'tickettypecode' : 'TAR'},
{'price' : 900, 'oneway' : 1, 'inboundJourneys' : [], "outboundJourneys": [18,19,20], 'tickettypecode' : 'GED'},
{'price' : 900, 'oneway' : 1, 'inboundJourneys' : [14,16,17], "outboundJourneys": [], 'tickettypecode' : 'GED'},
{'price' : 1200, 'oneway' : 1, 'inboundJourneys' : [], "outboundJourneys": [25], 'tickettypecode' : 'ABC'},
{'price' : 1200, 'oneway' : 1, 'inboundJourneys' : [32], "outboundJourneys": [], 'tickettypecode' : 'ABC'}
]

我需要的是:

其中 'price' 相等且 'tickettypecode' 相等且 'oneway' 相等,列表中有一个字典,因此结束于:

[
{'price' : 1800, 'oneway' : 1, 'inboundJourneys' : [9,10,11,14,16], "outboundJourneys": [3], 'tickettypecode' : 'SDS'},
{'price' : 2300, 'oneway' : 1, 'inboundJourneys' : [12,13,14], "outboundJourneys": ['6,8,9'], 'tickettypecode' : 'TAR'},
{'price' : 900, 'oneway' : 1, 'inboundJourneys' : [14,16,17], "outboundJourneys": [18,19,20], 'tickettypecode' : 'GED'},
{'price' : 1200, 'oneway' : 1, 'inboundJourneys' : [32], "outboundJourneys": [25], 'tickettypecode' : 'ABC'}
]

我已经尝试了很多方法,但我很难过。

最佳答案

假设合并列表中项目的顺序无关紧要,只需浏览列表中的每个项目,如果您以前没有看到它,就复制它,如果您有,则合并这些字段。

merged = {}

for item in original:
key = (item['price'], item['tickettypecode'], item['oneway'])
if key in merged:
for mergekey in ['inboundJourneys','outboundJourneys']:
# assign extended copy rather than using list.extend()
merged[key][mergekey] = merged[key][mergekey] + item[mergekey]
else:
merged[key] = item.copy()

mergedlist = merged.values()

关于python - 我如何遍历字典列表并合并字典以形成新的更短的字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9332639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com