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

Python:如何根据列表元素值获取字典键并按国家拆分城市列表

按国家拆分城市列表 + 字典值反向查键的Python实现

需求说明

  • 给定以国家为键、对应城市列表为值的字典 CountryDict,以及随机城市列表 CityList
  • 将 CityList 中的城市按所属国家拆分,输出对应国家及城市子列表
  • 核心问题:已知字典值列表中的元素,如何反向获取对应的字典键

现有代码问题

你提供的代码存在以下问题:

  1. 效率低下:多次嵌套遍历字典values,每次找到城市都要重新遍历整个字典,时间复杂度高
  2. 语法错误:Python3中 CountryDict.keys() 和 CountryDict.values() 返回视图对象而非列表,直接使用 keyList[pos] 会报错
  3. 逻辑冗余:重复嵌套循环导致代码可读性差

优化解决方案

步骤1:构建反向映射(高效查键)

先创建城市→国家的反向字典,查询单个城市所属国家的时间复杂度为O(1),大幅提升效率:

CountryDict = {
    "Spain" : ["Madrid", "Barcelona"],
    "Italy" : ["Rome", "Venice", "Milan"],
    "Germany": ["Munich"],
    "UK": ["London", "Liverpool"]
}
CityList = ["Venice", "Liverpool", "Madrid", "Barcelona"]

# 构建城市到国家的反向映射
city_to_country = {}
for country, cities in CountryDict.items():
    for city in cities:
        city_to_country[city] = country

步骤2:按国家归类城市

遍历输入的城市列表,利用反向映射将城市归类到对应国家的列表中:

# 初始化结果字典
result = {}
for city in CityList:
    # 通过反向映射快速获取国家
    country = city_to_country.get(city)
    if country:
        # 若国家不在结果中则初始化列表
        if country not in result:
            result[country] = []
        result[country].append(city)

步骤3:按示例格式输出

# 打印最终结果
for country, cities in result.items():
    print(f"{country}:")
    print(cities)
    print()

运行输出

Italy:
['Venice']

UK:
['Liverpool']

Spain:
['Madrid', 'Barcelona']

直接反向查键的方法(无需预构建映射)

如果字典规模很小,也可以直接遍历字典的键值对来查找对应国家,适合临时查询:

def find_country(city, country_dict):
    for country, cities in country_dict.items():
        if city in cities:
            return country
    # 找不到返回None或自定义提示
    return None

# 示例调用
print(find_country("Venice", CountryDict))  # 输出: Italy

内容的提问来源于stack exchange,提问作者Octavian Dărămuș

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:41:04