python中如何取嵌套字典中的多个值?
city_menu={"BJ":{"dongcheng":{"size":41.84,"people":91.9,"code":100010},
"xicheng":{"size":50.70,"people":124.3,"code":100032},
"chaoyang":{"size":470.8,"people":308.3,"code":100020}},
"GZ":{"yuexiu":{"size":33.80,"people":115,"code":510030},
"liwan":{"size":59.10,"Mpeople":89,"code":510145},
"tianhe":{"size":96.33,"people":143,"code":510630},
"haizhu":{"size":90.40,"people":155,"code":510220}},
"SZ":{"futian":{"size":78.66,"people":135.71,"code":518000},
"nanshan":{"size":185.49,"people":113.59,"code":518000},
"luohu":{"size":78.76,"people":95.37,"code":518001}}}
d={}
for k0,v0 in city_menu.items():
for k1,v1 in v0.items():
d[v1['code']]=k0+"-"+k1
def city():
qu=input('请输入邮政编码:')
if int(qu) in d:
return print('邮政编码为:%s 的城市是%s。' %(qu,d[int(qu)]))
else:
print('输入错误!')
感谢!
2019-07-23 · IT职业教育领导品牌
for district in city_menu.values():
for info in district.values():
code_list.append(info['code'])
print(code_list)
那如果用input()输入一个code值,怎么判断它属于哪个市哪个区呢?
code2district = {}
for district in city_menu.values():
for name, info in district.items():
code2district[info['code']] = name
code = int(input('请输入区号'))
try:
print(code2district[code])
except KeyError:
print('查无此区')