我有下面的代码,我正在尝试获取基于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)
首先迭代较大的num条目。传递
reverse=True
关键字参数使sorted
按相反顺序排序:相关问题 更多 >
编程相关推荐