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

Python字典键为城市元组时查询单个城市返回None如何解决

问题根因

你当前定义的字典以整个城市元组作为key,仅传入单个城市名'Athens'时,不存在匹配的key,因此查询返回None。

解决方案

方案1:重构字典为「单个城市对应GMT值」结构(推荐)

该方案利用字典O(1)的查询效率,后续查询速度最快,适合绝大多数场景:

# 原始分组数据
city_gmt_groups = {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
# 构建每个城市独立为key的字典
city_gmt_map = {}
for cities, gmt_val in city_gmt_groups.items():
    for city in cities:
        city_gmt_map[city] = gmt_val

# 直接查询即可得到对应值
print(city_gmt_map.get('Athens')) # 输出:2

方案2:不修改原字典,遍历匹配查询

如果必须保留原有的元组作为key的字典结构,可以写遍历逻辑匹配:

countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}

def query_gmt(city_name):
    for cities, gmt_val in countires.items():
        if city_name in cities:
            return gmt_val
    return None

print(query_gmt('Athens')) # 输出:2

该方案每次查询都要遍历所有字典键,适合数据量极小的临时场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:57:00