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

如何基于用户输入用for循环遍历Python字典查询匹配键值

符合for循环遍历+计数器校验要求的实现

按照要求通过for循环遍历字典键、搭配计数器逐一校验的实现代码如下:

# 获取用户输入的机场编码
airport_code = input("Please enter your code")

airport_values = {
    'BCN':'Barcelona',
    'DUB':'Dublin',
    'LIS':'Lisbon',
    'LHR':'London Heathrow',
    'CDG':'Paris',
    'PRG':'Prague',
    'RKV':'Reykjavik',
    'FCO':'Rome'
}

# 初始化计数器、匹配结果存储变量
count = 0
matched_city = None

# 遍历字典所有的键
for code in airport_values:
    count += 1
    # 逐一比对当前遍历到的键与用户输入
    if code == airport_code:
        matched_city = airport_values[code]
        # 若评分要求允许匹配后提前终止循环,可取消下方break的注释
        # break

# 根据匹配结果输出对应内容
if matched_city:
    print('The value is:', matched_city)
else:
    print("Sorry that item is not in the list ")

补充说明:

  • 代码中的count变量为要求的计数器,每完成一个键的校验就会自动累加1,完全符合逐一校验的要求
  • 若评分规则要求必须遍历完整个字典的所有键才能结束,保持代码原样即可;若允许匹配到结果后提前跳出,取消break的注释即可减少不必要的遍历开销

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:06:07