Python: finding a multidimensional dictionary for a key

I am using the Python JSON decoding library with the Google Maps API. I am trying to get the zip code of an address, but sometimes it is in a different dictionary. Here are two examples (I clipped JSON to what is appropriate):

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

( View full JSON )

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

( View full JSON )

So zipcodes:

zipcode1 = placemark1['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['PostalCode']['PostalCodeNumber']
zipcode2 = placemark2['AddressDetails']['Country']['AdministrativeArea']['Locality']['PostalCode']['PostalCodeNumber']

Now I thought that I should just look for a multidimensional dictionary for a key "PostalCodeNumber". Does anyone know how to do this? I want it to look something like this:

>>> 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
+3
source share
2 answers
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

gives all matching values ​​in the tree:

>>> list(treeGet(zipcode1, 'PostalCodeNumber'))
['94043']
>>> list(treeGet(zipcode2, 'PostalCodeNumber'))
['11201']
+1
source
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)

gives

94043
11201
None
None
None
+2
source

Source: https://habr.com/ru/post/1793697/


All Articles