You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

基于主字典索引访问嵌套字典及关联值查询问题

解决嵌套字典的两个匹配问题

嘿,这两个问题其实都是通过遍历嵌套结构里的字典,匹配目标键值对来获取对应数据的,我给你一步步拆解:

首先咱们先明确数据结构(我根据你的问题描述模拟了output的示例,和你的实际结构应该是类似的):

output = [
    {"photo_id": "img_001", "sample_id": "s_123", "f_id": 1234, "photo_desc": "A"},
    {"photo_id": "img_002", "sample_id": "s_456", "f_id": 1366, "photo_desc": "C"},
    {"photo_id": "img_003", "sample_id": "s_789", "f_id": 5678, "photo_desc": "B"}
]

问题1:已知Photo_id,获取同索引下的sample_id

思路很简单:遍历output列表里的每一个字典,找到photo_id和目标值匹配的项,然后直接取出对应的sample_id即可。

代码实现(直接遍历)

# 目标Photo_id
target_photo_id = "img_002"

for item in output:
    # 检查当前字典的photo_id是否匹配
    if item.get("photo_id") == target_photo_id:
        matched_sample_id = item.get("sample_id")
        print(f"匹配到的sample_id是:{matched_sample_id}")
        break  # 找到就停止遍历,提升效率
else:
    # 如果遍历完都没找到,输出提示
    print(f"没有找到photo_id为{target_photo_id}的条目")

封装成函数(方便复用)

如果你需要多次调用,可以把逻辑封装成函数:

def get_sample_id_by_photo_id(output_data, target_photo_id):
    for item in output_data:
        if item.get("photo_id") == target_photo_id:
            return item.get("sample_id")
    return None  # 没找到返回None

# 调用函数
sample_id = get_sample_id_by_photo_id(output, "img_002")
print(f"对应sample_id:{sample_id}")  # 输出:对应sample_id:s_456

问题2:已知f_id=1366,查找对应photo_desc

和第一个问题逻辑完全一致,只是匹配的键从photo_id换成了f_id,目标值是1366,最后取photo_desc

代码实现(直接遍历)

# 目标f_id
target_f_id = 1366

for item in output:
    if item.get("f_id") == target_f_id:
        matched_photo_desc = item.get("photo_desc")
        print(f"匹配到的photo_desc是:{matched_photo_desc}")
        break
else:
    print(f"没有找到f_id为{target_f_id}的条目")

封装成函数

def get_photo_desc_by_f_id(output_data, target_f_id):
    for item in output_data:
        if item.get("f_id") == target_f_id:
            return item.get("photo_desc")
    return None

# 调用函数
photo_desc = get_photo_desc_by_f_id(output, 1366)
print(f"对应photo_desc:{photo_desc}")  # 输出:对应photo_desc:C

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

火山引擎 最新活动