Python:如何将同日期元组列表转换为含唯一日期的单字典列表?
将元组列表转换为含统一日期的单字典列表
假设你的原始数据是:
query_result = [(3, 'base-certificate', 8, 2022), (2, 'case-certificate', 8, 2022), (3, 'standard-certificate', 8, 2022)]
针对单日期场景的修改方案
如果所有元组的日期都一致,直接遍历元组构建字典,最后统一添加日期字段即可:
def convert_query_data_for_frontend(query_result): result_dict = {} for value, cert_name, month, year in query_result: result_dict[cert_name] = value result_dict['date'] = [month, year] return [result_dict]
调用这个函数后,会返回你期望的结果:
[{'base-certificate': 3, 'case-certificate': 2, 'standard-certificate': 3, 'date': [8, 2022]}]
支持多日期场景的通用方案
如果未来数据可能包含不同日期的元组,可以按日期分组,确保每个日期对应一个包含所有证书的字典:
def convert_query_data_for_frontend(query_result): grouped_data = {} for value, cert_name, month, year in query_result: date_key = (month, year) # 若该日期未初始化字典,先创建并添加日期字段 if date_key not in grouped_data: grouped_data[date_key] = {'date': [month, year]} # 添加当前证书的键值对 grouped_data[date_key][cert_name] = value # 将分组后的字典值转为列表返回 return list(grouped_data.values())
比如如果有不同日期的数据,这个函数会生成对应数量的字典,每个字典包含对应日期的所有证书信息。
内容的提问来源于stack exchange,提问作者dave
相关产品推荐
相关产品推荐

