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

如何提取Python嵌套字典的指定目标值并支持多键通用取值

Python 嵌套字典目标值提取方法

结构说明

你提供的字典为两层嵌套结构:

  • 外层键:题目文本
  • 外层值:内层字典,内层键为选项列表的字符串形式,内层值为对应选项组的正确答案

通用实现代码

def get_correct_answer(question_dict: dict, target_question: str = "", target_options: list = None):
    """
    从匹配结构的字典中提取对应正确答案,支持多场景适配
    :param question_dict: 原始存储题目的字典
    :param target_question: 可选,要提取答案的目标题目文本,不传则返回所有题目答案
    :param target_options: 可选,对应题目下的目标选项列表,不传则返回该题目下所有选项组的答案
    """
    # 未指定题目时返回所有题目答案
    if not target_question:
        return question_dict
    # 匹配目标题目
    inner_option_map = question_dict.get(target_question)
    if not inner_option_map:
        return "未查询到对应题目"
    # 未指定选项组时返回当前题目所有答案
    if not target_options:
        return inner_option_map
    # 匹配指定选项组的答案
    option_key = str(target_options)
    return inner_option_map.get(option_key, "未查询到对应选项组的答案")

使用示例

针对你给出的示例字典,提取标注加粗的目标值调用方式如下:

# 示例字典
demo_dict = {
    "Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---.": {
        "['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']": "1: liquid; 2: evaporation",
        "['1: liquid; 2: deposition', '1: liquid; 2: sublimation', '1: solid; 2: deposition', '1: solid; 2: sublimation']": "1: solid; 2: sublimation"
    }
}

# 提取目标加粗值
target_ques = "Complete the following statement: changing state from ---(1)--- to gas is known as ---(2)---."
target_opts = ['1: liquid; 2: evaporation', '1: liquid; 2: melting', '1: solid; 2: evaporation', '1: solid; 2: melting']
target_value = get_correct_answer(demo_dict, target_ques, target_opts)
print(target_value)

运行后输出结果为1: liquid; 2: evaporation,即你需要的目标值。

适配说明

该方法不需要硬编码固定键名,只要是相同结构的字典,都可以通过传入对应题目、选项参数提取目标值,支持单题单选项组、单题全选项组、全题全选项组三种查询场景。

内容的提问来源于stack exchange,提问作者Bigboyal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:54:08