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

如何遍历Python字典第二个值实现匹配条目查询

问题描述

需要实现一个可以检查并返回匹配专辑记录的函数,当前使用的字典存储了专辑名、歌曲数两类信息,原有代码无法正确遍历匹配到对应记录,也没法顺利取出歌曲数字段。
原有代码如下:

def make_album(artist, album_title, songs = None):
    A = {
    'artist1': 'album1', 'songs': '1'
    }
    
    B = {
    'artist2': 'album2', 'songs': '2'
    }
    
    C = {
    'artist3': 'album3', 'songs': '3'
    }

    dicts = [A, B, C]
    
    for dictionary in dicts:
        for key, value in dictionary.items():
            if key == artist and value == album_title:
                print(dictionary)       
make_album('artist2', 'album2')
问题原因

原有字典结构设计不规范:每个专辑条目把歌手名直接作为字典键、专辑名作为对应值,只有songs是固定键名,这种动态键名的设计既没法稳定按字段取值,还需要额外遍历所有键值对做判断,很容易出问题。

修正代码

统一每个专辑条目的字段键名,所有条目固定使用artist存歌手名、album_title存专辑名、songs存歌曲数,匹配时直接通过固定键取值比对即可,不需要嵌套遍历字典键值:

def make_album(artist, album_title, songs=None):
    # 统一字典字段结构,所有条目用固定key
    album_list = [
        {'artist': 'artist1', 'album_title': 'album1', 'songs': '1'},
        {'artist': 'artist2', 'album_title': 'album2', 'songs': '2'},
        {'artist': 'artist3', 'album_title': 'album3', 'songs': '3'}
    ]
    
    for album in album_list:
        # 直接按固定key取值判断,不需要遍历所有键值
        if album['artist'] == artist and album['album_title'] == album_title:
            # 如果需要取歌曲数,直接用album['songs']即可获取
            print("匹配到的专辑记录:", album)
            return album
    # 无匹配时返回None
    return None

make_album('artist2', 'album2')

运行后输出:

匹配到的专辑记录: {'artist': 'artist2', 'album_title': 'album2', 'songs': '2'}
改动说明
  • 统一了专辑字典的键名规则,所有存储条目字段固定,不会出现键名随内容变化的问题,后续取songs等字段直接按键名取值即可
  • 删除了冗余的内层字典遍历逻辑,判断逻辑更简洁,运行效率更高
  • 匹配到结果后直接返回对应字典,方便后续对匹配到的记录做其他处理,而不只是打印输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:24:17