Python:在多维字典中搜索密钥

时间:2011-02-21 21:00:18

标签: algorithm json dictionary python

我正在使用Python的JSON decoding library和Google Maps API。我试图获取地址的邮政编码,但它有时会驻留在不同的字典键中。这里有两个例子(我已将JSON修剪为相关内容):

placemark1 = {
  "AddressDetails": {
    "Country": {
      "AdministrativeArea": {
        "SubAdministrativeArea": {
          "Locality": {
            "PostalCode": {
              "PostalCodeNumber": "94043"
            }
          }
        }
      }
    }
  }
}

View full JSON

placemark2 = {
  "AddressDetails": {
    "Country" : {
      "AdministrativeArea" : {
        "Locality" : {
          "PostalCode" : {
            "PostalCodeNumber" : "11201"
          }
        }
      }
    }
  }
}

View full JSON

所以zipcodes:

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

2 个答案:

答案 0 :(得分:2)

def get_key(key,dct):
    if key in dct:
        return dct[key]
    for k in dct:
        try:
            return get_key(key,dct[k])
        except (TypeError,ValueError):
            pass
    else:
        raise ValueError

placemark1 = {
  "AddressDetails": {
    "Country": {
      "AdministrativeArea": {
        "SubAdministrativeArea": {
          "Locality": {
            "PostalCode": {
              "PostalCodeNumber": "94043"
            }
          }
        }
      }
    }
  }
}

placemark2 = {
  "AddressDetails": {
    "Country" : {
      "AdministrativeArea" : {
        "Locality" : {
          "PostalCode" : {
            "PostalCodeNumber" : "11201"
          }
        }
      }
    }
  }
}

just_being_a_dict = {}
just_a_list = []
counter_dict = {'Name': 'I like messing things up'}

for x in (placemark1, placemark2, just_being_a_dict, just_a_list, counter_dict):
    try:
        print(get_key('PostalCodeNumber', x))
    except ValueError:
        print(None)

产量

94043
11201
None
None
None

答案 1 :(得分:1)

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']