首页 > 解决方案 > 有什么方法可以从 python 中的值中获取键?(字典)

问题描述

这个问题似乎有点奇怪,因为我知道字典不打算根据值而不是键来使用我最近遇到了某些问题,以尽量减少表格填写过程,因为如果提供了某些国家城市,那么我需要自动填写国家和大陆那个用户。我得到以下 Json 供我参考。

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

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

标签: pythonjsondictionary

解决方案


您可以遍历数据并“逆向工程”字典:

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)

推荐阅读