Python嵌套字典列表操作:删除指定键与提取text键值
问题1:如何用Python删除嵌套字典列表中指定键的所有实例?
用递归遍历嵌套结构是最直接的方案,能处理任意层级的字典和列表:
def remove_key(data, target_key): if isinstance(data, dict): # 转成列表遍历,避免修改字典时触发迭代错误 for key in list(data.keys()): if key == target_key: del data[key] else: remove_key(data[key], target_key) elif isinstance(data, list): for item in data: remove_key(item, target_key) return data # 示例用法 nested_data = [{"a": 1, "b": 2}, {"c": {"b": 3}, "d": [{"b": 4}]}] result = remove_key(nested_data, "b") print(result) # 输出: [{'a': 1}, {'c': {}, 'd': [{}]}]
这个函数会逐层检查每个元素:碰到字典就删除目标键,再递归处理剩余值;碰到列表就逐个递归处理内部元素,确保所有层级的目标键都被清理。
问题2:按原有顺序提取API返回JSON中所有"text"键的对应值
用递归遍历按访问顺序收集结果,能完美保留原JSON的顺序:
import json def extract_text(data, result=None): if result is None: result = [] if isinstance(data, dict): # 碰到"text"键就把值加入结果列表 if "text" in data: result.append(data["text"]) # 递归处理字典的所有值 for value in data.values(): extract_text(value, result) elif isinstance(data, list): # 递归处理列表中的每个元素 for item in data: extract_text(item, result) return result # 解析API返回的JSON字符串 json_str = ''' { "version": 1, "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "ABC - 1234" }, { "type": "hardBreak" }, { "type": "text", "text": "EFG - 648" } ] }, { "type": "paragraph", "content": [ { "type": "text", "text": "Above EFG is a reissue of 4 payments, that status is at Issued/Requested. " }, { "type": "hardBreak" }, { "type": "text", "text": "This payment has not been issued & an payfac file has not been produced. " }, { "type": "hardBreak" }, { "type": "text", "text": "Please can you:" } ] }, { "type": "bulletList", "content": [ { "type": "listItem", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "explain what the status \"Issue/Requesed\" means" } ] } ] }, { "type": "listItem", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "explain how this status occured" } ] } ] }, { "type": "listItem", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "would there be any reconcilation issues if I was to change the status to \"Paid/None\" on 1-Jan?" } ] } ] } ] }, { "type": "paragraph", "content": [ { "type": "text", "text": "Thank you." } ] } ] } ''' data = json.loads(json_str) text_list = extract_text(data) for text in text_list: print(text)
运行后会按原JSON的顺序输出所有"text"值:
ABC - 1234 EFG - 648 Above EFG is a reissue of 4 payments, that status is at Issued/Requested. This payment has not been issued & an payfac file has not been produced. Please can you: explain what the status "Issue/Requesed" means explain how this status occured would there be any reconcilation issues if I was to change the status to "Paid/None" on 1-Jan? Thank you.
内容的提问来源于stack exchange,提问作者user391014
相关产品推荐
相关产品推荐

