可以使用递归函数来遍历整个嵌套层次不同的字典,收集所有感兴趣的键值对,最终得到一个非嵌套结构的字典:
(一般用于处理爬取的json数据,因为有些结构真的蛮怪的(メ3[____]
def extract_key_value_pairs(nested_dict, keys_to_extract): """ 从嵌套字典中提取特定的键值对,并返回一个非嵌套结构的字典 nested_dict: 嵌套字典 keys_to_extract: 要提取的键的列表(支持嵌套键,如 'outer_key.inner_key')return: 一个非嵌套结构的字典,包含所有提取的键值对 """ flat_dict = {} def extract_from_dict(d, prefix=''): for key, value in d.items(): full_key = prefix + key if prefix else key if full_key in keys_to_extract: flat_dict[full_key] = value if isinstance(value, dict): extract_from_dict(value, full_key + '.') extract_from_dict(nested_dict) return flat_dict # 示例嵌套字典
nested_dict = { 'a': 1, 'b': { 'c': 2, 'd': { 'e': 3 } }, 'f': 4, 'g': { 'h': 5 }
} # 要提取的键
keys_to_extract = ['a', 'b.c', 'b.d.e', 'g.h'] # 提取键值对
result_dict = extract_key_value_pairs(nested_dict, keys_to_extract) print(result_dict)'''输出:
{'a': 1, 'b.c': 2, 'b.d.e': 3, 'g.h': 5}'''