如何匹配不同词典键值

2024-09-30 16:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,我正在尝试获取基于num键值测试的外部dict键,例如,如果chan\u num是248,我想获取'lifestyle&;文化的关键,但目前我总是匹配的第一项

我怎样才能做到这一点

chan_tags = {
    'Entertainment': {'num': 101, 'on': 1},
    'Lifestyle and Culture': { 'num': 240,  'on': 1 },
    'Movies': { 'num': 301,  'on': 1 }
    }

def chanToTag(chan_num, chan_tags):
    tag = ""
    for n in sorted(chan_tags, key=lambda k: chan_tags[k]['num']):
        if  chan_num >= chan_tags[n]['num']:
                tag = n            
                break
    return tag

tag_name = chanToTag(248, chan_tags)

print(tag_name)

Tags: 代码nameontagtags文化numdict
1条回答
网友
1楼 · 发布于 2024-09-30 16:21:43

首先迭代较大的num条目。传递reverse=True关键字参数使sorted按相反顺序排序:

def chanToTag(chan_num, chan_tags):
    for n in sorted(chan_tags, key=lambda k: chan_tags[k]['num'], reverse=True):
        if chan_num >= chan_tags[n]['num']:
            return n
    return ''

相关问题 更多 >