Python中如何按指定key拆分字典并解析数据,提取会话最新轮次记录
多轮会话数据处理实现方案
原代码问题分析
- 仅初始化了单个数据字典,每次循环都会覆盖原有内容,因此最终只能输出一条结果
- 内层
for conversations in conversationID逻辑错误,conversationID是字符串类型,遍历只会逐个取字符,没有实际业务意义 - 代码中
customer_name、customer_intention、customer_property没有提前定义,直接判断会抛出变量未定义报错
方案1:提取每个会话ID对应最大轮次的条目
实现逻辑:先遍历所有会话记录,按会话ID分组存储最大轮次对应的记录即可。
# 用字典存储每个会话ID的最大轮次记录 max_counter_records = {} for convo in conversation_counter: convo_id = convo['conversation_id'] # 转成整数比较轮次大小,避免字符串比较的逻辑问题 current_counter = int(convo['dialog_counter']) # 如果该会话ID还没存,或者当前轮次比已存的轮次大,就更新 if convo_id not in max_counter_records or current_counter > int(max_counter_records[convo_id]['dialog_counter']): # 只保留需要的字段 max_counter_records[convo_id] = { 'conversation_id': convo_id, 'customer_name': convo['customer_name'], 'customer_intention': convo['customer_intention'], 'customer_property': convo['customer_property'] } # 输出结果(如果需要列表格式可以直接取values) result = list(max_counter_records.values()) for item in result: print(item)
输出示例:
{'conversation_id': '4850dd66-05b9-43e9-b546-e4976c9c29b6', 'customer_name': 'David', 'customer_intention': 'buy', 'customer_property': 'house'} {'conversation_id': 'dbec6faa-16cb-416a-8653-ffc36174ecee', 'customer_name': 'David', 'customer_intention': 'buy', 'customer_property': 'house'}
方案2:按会话ID拆分得到独立子字典集合
实现逻辑:以会话ID为key,同ID的所有原始条目组成的列表为value,存储为字典即可。
convo_groups = {} for convo in conversation_counter: convo_id = convo['conversation_id'] if convo_id not in convo_groups: convo_groups[convo_id] = [] convo_groups[convo_id].append(convo) # 输出示例:打印每个会话ID对应的所有条目数量 for convo_id, records in convo_groups.items(): print(f"会话ID:{convo_id},共{len(records)}轮对话")
补充:如需累计每个会话的最新非空字段值
如果不需要完全取最大轮次的所有字段,而是优先取各字段最后一次出现的非空值,可以用如下逻辑:
latest_records = {} for convo in conversation_counter: convo_id = convo['conversation_id'] if convo_id not in latest_records: latest_records[convo_id] = { 'conversation_id': convo_id, 'customer_name': '', 'customer_intention': '', 'customer_property': '' } # 字段非空才更新 if convo['customer_name'].strip(): latest_records[convo_id]['customer_name'] = convo['customer_name'] if convo['customer_intention'].strip(): latest_records[convo_id]['customer_intention'] = convo['customer_intention'] if convo['customer_property'].strip(): latest_records[convo_id]['customer_property'] = convo['customer_property'] result = list(latest_records.values())
内容的提问来源于stack exchange,提问作者Brandon Jacobson
相关产品推荐
相关产品推荐

