我正在将Python的JSON decoding library与Google Maps API结合使用.我正在尝试获取地址的邮政编码,但有时它位于不同的字典键中.这是两个示例(我将JSON修剪为相关的内容):
placemark1 = {
"AddressDetails": {
"Country": {
"AdministrativeArea": {
"SubAdministrativeArea": {
"Locality": {
"PostalCode": {
"PostalCodeNumber": "94043"
}
}
}
}
}
}
}
placemark2 = {
"AddressDetails": {
"Country" : {
"AdministrativeArea" : {
"Locality" : {
"PostalCode" : {
"PostalCodeNumber" : "11201"
}
}
}
}
}
}
因此,邮政编码:
zipcode1 = placemark1['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['PostalCode']['PostalCodeNumber']
zipcode2 = placemark2['AddressDetails']['Country']['AdministrativeArea']['Locality']['PostalCode']['PostalCodeNumber']
现在我在想,也许我应该只在多维词典中搜索“ PostalCodeNumber”键.有谁知道如何实现这一目标?我希望它看起来像这样:
>>> just_being_a_dict = {}
>>> just_a_list = []
>>> counter_dict = {'Name': 'I like messing things up'}
>>> get_key('PostalCodeNumber', placemark1)
"94043"
>>> get_key('PostalCodeNumber', placemark2)
"11201"
>>> for x in (just_being_a_dict, just_a_list, counter_dict):
... get_key('PostalCodeNumber', x) is None
True
True
True
解决方法:
from collections import Mapping
zipcode1 = {'placemark1':{'AddressDetails':{'Country':{'AdministrativeArea':{'SubAdministrativeArea':{'Locality':{'PostalCode':{'PostalCodeNumber':"94043"}}}}}}}}
zipcode2 = {'placemark2':{'AddressDetails':{'Country':{'AdministrativeArea':{'Locality':{'PostalCode':{'PostalCodeNumber':'11201'}}}}}}}
def treeGet(d, name):
if isinstance(d, Mapping):
if name in d:
yield d[name]
for it in d.values():
for found in treeGet(it, name):
yield found
产生树中所有匹配的值:
>>> list(treeGet(zipcode1, 'PostalCodeNumber'))
['94043']
>>> list(treeGet(zipcode2, 'PostalCodeNumber'))
['11201']