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

如何使用Python Dict与List匹配City值并返回对应完整记录

问题修正:匹配任意层级city字段返回对应完整记录

需求说明

现有两个变量a和result,若result与变量a中任意层级的city字段内的记录匹配,则返回a中对应的完整顶级记录(即output数组中的对应元素)。

给定数据

a = {
    "output": [
        {"name": "India",
        "state": [
            {
                "city": ["c", "d" ]
            }
        ],
        "city": [
            "g",
            "h"
        ]},
        {"name": "Telangana",
        "state": [
            {
                "city": ["a", "b" ]
            }
        ],
        "city": [
            "e",
            "f"
        ]}
        ]
    }
result = "e"

预期结果

  • 当result="e"时,返回:
{"name": "Telangana",
            "state": [
                {
                    "city": ["a", "b" ]
                }
            ],
            "city": [
                "e",
                "f"
            ]}
  • 当result="d"时,返回:
{"name": "India",
            "state": [
                {
                    "city": ["c", "d" ]
                }
            ],
            "city": [
                "g",
                "h"
            ]}

原代码问题分析

原代码存在以下问题:

  • 直接使用全局变量a,未利用传入的data参数,逻辑耦合严重;
  • 递归调用参数错误,item['state']是数组,未做遍历就传入递归;
  • 找到匹配后仍继续递归,且递归返回值处理混乱,会导致重复输出;
  • 没有正确终止逻辑,找到匹配后未及时返回。

修正后的代码

def find_matching_record(data, target):
    # 遍历output中的每一条顶级记录
    for record in data["output"]:
        # 检查当前记录的city字段
        if target in record.get("city", []):
            return record
        # 遍历当前记录下的state,检查每个state内的city
        for state in record.get("state", []):
            if target in state.get("city", []):
                return record
    # 无匹配记录时返回None
    return None

# 调用示例
result = "e"
matching_record = find_matching_record(a, result)
if matching_record:
    print(matching_record)

代码说明

  • 函数接收data和target参数,避免全局变量依赖;
  • 先检查顶级记录的city字段,匹配则直接返回该记录;
  • 若顶级city无匹配,遍历该记录下的state数组,检查每个state内的city,匹配则返回顶级记录;
  • 找到匹配后立即返回,终止后续遍历,提升效率;
  • 未找到匹配时返回None,方便后续判断处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:15:19