如何从Python嵌套字典中提取指定键及其对应值?
如何从嵌套字典中提取指定键生成扁平字典
方案1:直接构建(最适合初学者,结构固定时首选)
你的字典结构固定,直接通过层级键访问对应值,手动构建新字典即可,逻辑清晰不易出错:
dict_ = { "timestamp": "2022-11-18T10: 10: 49.301Z", "name" : "example", "person":{ "birthyear": "2002", "birthname": "Examply" }, "order":{ "orderId": "1234", "ordername": "onetwothreefour" } } # 直接提取需要的键值对构建新字典 new_dict = { "timestamp": dict_["timestamp"], "birthyear": dict_["person"]["birthyear"], "birthname": dict_["person"]["birthname"], "orderId": dict_["order"]["orderId"] } print(new_dict) # 输出: {"timestamp": "2022-11-18T10: 10: 49.301Z", "birthyear": "2002", "birthname": "Examply", "orderId": "1234"}
方案2:通用提取函数(适合需多次提取或结构可能变化的场景)
如果以后需要提取更多嵌套键,或者字典结构有微调,可以写一个简单的函数批量处理:
def extract_nested_keys(source_dict, key_paths): result = {} for target_key, path in key_paths.items(): current_value = source_dict # 按路径逐层深入字典取值 for key_part in path: current_value = current_value[key_part] result[target_key] = current_value return result # 定义要提取的目标键和对应的嵌套路径 key_mapping = { "timestamp": ["timestamp"], "birthyear": ["person", "birthyear"], "birthname": ["person", "birthname"], "orderId": ["order", "orderId"] } new_dict = extract_nested_keys(dict_, key_mapping)
为什么你之前的代码无效?
你用的字典推导式 {key: msg[key] for key in msg.keys() & {'timestamp', ...}} 只能匹配顶层字典的键,而birthyear、birthname这些键属于子字典person,不在顶层msg.keys()集合里,所以完全匹配不到,自然无法提取对应值。
内容的提问来源于stack exchange,提问作者JazCodes
相关产品推荐
相关产品推荐

