You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:05:23