有什么方法可以从python中的值中获取密钥吗?(字典)

2024-09-30 06:11:37 发布

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

这个问题似乎有点奇怪,因为我知道字典不是基于值而不是键来使用的。我最近遇到了一些问题,将表单填写过程最小化,好像提供了某些国家/城市,那么我需要为该用户自动完成国家/地区和大陆。 我得到了以下Json作为参考

[{
        "Asia": {
            "Japan": [
                "tokyo",
                "hirohima",
            ]
        }
    },
    {
        "Europe": {
            "England": [
                "Manchester",
                "London",
                "South gate",
            ]
        }
    }
]

假设用户城市是伦敦,我能得到英国和欧洲作为输出吗?还是我的json格式错误


Tags: 用户json表单字典过程国家地区大陆
3条回答

您可以创建城市到国家/地区元组的反向索引。由于城市名称不是唯一的,您可能在多个国家/地区拥有相同的城市名称。您可以通过索引到国家/地区列表来解决此问题。当您获得数据时,您可以这样做一次,然后在需要时可以快速查找数据

from collections import defaultdict

data = [{
        "Asia": {
            "Japan": [
                "tokyo",
                "hirohima",
            ]
        }
    },
    {
        "Europe": {
            "England": [
                "Manchester",
                "London",
                "South gate",
            ]
        }
    }
]

reverse_index = defaultdict(list)

for region_dict in data:
    for region, country_dict in region_dict.items():
        for country, city_list in country_dict.items():
            for city in city_list:
                reverse_index[city].append((region, country))
            
for city, refs in reverse_index.items():
    print(city, refs)

您可以循环浏览数据并对字典进行“反向工程”:

city = "London"
for d in data:
    for continent, countries in d.items():
        for country, cities in countries.items():
            if "London" in cities:
                print(country, continent)

要获取国家名称和大陆名称,您的json文件必须采用以下格式:

[{"ContinentName":"Asia","country":{"countryName":"Japan","cities":["tokyo","hirohima"]}},{"ContinentName":"Europe","country":{"countryName":"England","cities":["london","south gate","Manchester"]}}]

相关问题 更多 >

    热门问题