如何用Python列表推导式从JSON中提取多组键值到同一变量
解决方案
1. 灵活提取多字段(支持后续扩展)
先定义需要提取的字段列表,后续新增字段只需修改这个列表即可,不用改动核心提取逻辑:
# 定义要提取的字段,后续添加字段直接在这里追加 target_fields = ['descr', 'value', 'annotation', 'childAction'] # 提取数据,生成字典列表(每个字典对应一组完整数据) extracted_data = [ {field: item['fvRsNodeAtt']['attributes'][field] for field in target_fields} for item in item_out_list ]
如果担心部分字段缺失导致KeyError,可以用get方法设置默认值(比如空字符串):
extracted_data = [ {field: item['fvRsNodeAtt']['attributes'].get(field, '') for field in target_fields} for item in item_out_list ]
2. 生成“descr value”格式的字符串
如果需要直接输出类似apple mango的拼接字符串,可修改推导式:
formatted_strings = [ f"{item['fvRsNodeAtt']['attributes']['descr']} {item['fvRsNodeAtt']['attributes']['value']}" for item in item_out_list ] # 输出结果:['apple mango', 'peach banana'] print(formatted_strings)
3. 保存到CSV文件
利用Python内置的csv模块,结合上面的字典列表,可以快速生成带表头的CSV文件:
import csv target_fields = ['descr', 'value', 'annotation', 'childAction'] extracted_data = [ {field: item['fvRsNodeAtt']['attributes'][field] for field in target_fields} for item in item_out_list ] # 写入CSV with open('output.csv', 'w', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=target_fields) writer.writeheader() # 写入表头行 writer.writerows(extracted_data) # 批量写入数据行
生成的CSV内容示例:
descr,value,annotation,childAction apple,mango,, peach,banana,,
内容的提问来源于stack exchange,提问作者Hooch_dgb
相关产品推荐
相关产品推荐

