Accessings deeply nested dictionary/list elements/values in Python
Question: I've been racking my brain on this problem and the logic needed to step
through this output from Google Maps API.

Essentially I'm using google maps Distance_Matrix: Here is an example of the
returned information from a call of the API for distance/time between two
addresses, which I've assigned to variable _distanceMatrixReturn_ for this
example.

    
    
      distanceMatrixReturn = {
                {'destination_addresses': ['This would be ADDRESS 1'],
                'status': 'OK',
                'rows': [
                {
                    'elements': [
                     {
                         'duration_in_traffic': {
                               'text': '10 mins', 'value': 619},
                                'status': 'OK',
                                 'distance': {'text': '2.8 mi', 'value': 4563},
                                 'duration': {'text': '9 mins', 'value': 540}}]}], 
                                }]
                  }], 
        'origin_addresses': ['This would be ADDRESS 2'] 
    }
    

Now, being a python newbie struggling with nested dictionaries and lists; Here
is my thought process:

I want to access the value `'2.8 mi'` that to my impression, is within a
dictionary tied to the key 'text', which is in turn inside a dictionary
assigned to the key `'distance'`, which is in another dictionary with the key
`'duration_in_traffic'`.

The key `'duration_in_traffic'` seems to be within a list, tied to the
dictionary key `'elements'`, which in turn is in a list tied to another
dictionary key, `'rows'`.

Now, this seems very very convoluted and there must be an easy way to handle
this situation, or maybe my logic is just off about the nested within nested
elements and the method of accessing them.

For example, among other posts here, I've read the following to try and figure
out the process of intepreting something seemingly similar. [How to access a
dictionary key value present inside a
list?](http://stackoverflow.com/questions/6521892/how-to-access-a-dictionary-
key-value-present-inside-a-list)

Please let me know if I structured the distanceMatrixReturn on this post
poorly. I spaced it to try and make it more readable, I hope I've achieved
that.


Answer: Your dictionary is broken, so it's hard to imagine the right path. Anyway.

    
    
    from operator import getitem
    
    path = ["rows", 0, "elements", 0, "duration_in_traffic", "distance", "text"]
    
    reduce(getitem, path, distanceMatrixReturn)  # -> "2.8 mi"
    

On Python 3 you will have to import `reduce` from `functools` first.

