Python如何通过字典的值获取对应键?实现城市反向查询所属国家大洲
问题解答
现有结构可行性说明
你当前使用的JSON格式是合法的,完全可以实现根据城市查询对应国家、大洲的需求,只是无法通过字典的常规键值查找直接获取结果,需要嵌套遍历处理,具体查询逻辑如下:
- 遍历外层数组的每一个元素,每个元素对应1个大洲的数据集
- 提取当前元素的键作为大洲名称,再遍历该键对应的值(国家数据集)
- 提取当前国家数据集的键作为国家名称,检查对应城市数组是否包含用户输入的城市
- 匹配到目标城市后,直接返回当前的国家、大洲名称即可,无需继续遍历
注意:你当前的城市数据大小写不统一(比如
tokyo全小写、London首字母大写),建议存储时统一城市名的大小写格式,查询时先将用户输入转换为对应格式再做匹配,避免匹配失败。
以下是JavaScript版本的简单实现示例:
const regionData = [{ "Asia": { "Japan": [ "tokyo", "hirohima", ] } }, { "Europe": { "England": [ "Manchester", "London", "South gate", ] } } ]; function getRegionByCity(cityName) { // 统一转小写匹配,也可转大写,和存储规则对齐即可 const targetCity = cityName.toLowerCase(); for (const continentItem of regionData) { const continentName = Object.keys(continentItem)[0]; const countryData = continentItem[continentName]; for (const countryName of Object.keys(countryData)) { const cityList = countryData[countryName].map(item => item.toLowerCase()); if (cityList.includes(targetCity)) { return { country: countryName, continent: continentName } } } } return null; } // 测试查询London console.log(getRegionByCity('London')); // 输出 {country: 'England', continent: 'Europe'}
更高性能的结构优化方案
如果表单补全的查询频率较高,嵌套遍历的性能会随着数据量增长明显下降,建议直接将城市作为顶级键重构JSON结构,实现O(1)复杂度的直接查询:
{ "tokyo": { "country": "Japan", "continent": "Asia" }, "hirohima": { "country": "Japan", "continent": "Asia" }, "manchester": { "country": "England", "continent": "Europe" }, "london": { "country": "England", "continent": "Europe" }, "south gate": { "country": "England", "continent": "Europe" } }
重构后查询逻辑非常简单,直接用城市名作为键取值即可,适合实时性要求高的表单补全场景。
内容的提问来源于stack exchange,提问作者lord stock
相关产品推荐
相关产品推荐

