title: Xpath like query for nested python dictionaries
body: <p>Is there a way to define a XPath type query for nested python dictionaries.</p>
  
  <p>Something like this:</p>
  
  <pre><code>foo = {
    'spam':'eggs',
    'morefoo': {
                 'bar':'soap',
                 'morebar': {'bacon' : 'foobar'}
                }
     }
  
  print( foo.select("/morefoo/morebar") )
  
  &gt;&gt; {'bacon' : 'foobar'}
  </code></pre>
  
  <p>I also needed to select nested lists ;)</p>
  
  <p>This can be done easily with @jellybean's solution:</p>
  
  <pre><code>def xpath_get(mydict, path):
      elem = mydict
      try:
          for x in path.strip("/").split("/"):
              try:
                  x = int(x)
                  elem = elem[x]
              except ValueError:
                  elem = elem.get(x)
      except:
          pass
  
      return elem
  
  foo = {
    'spam':'eggs',
    'morefoo': [{
                 'bar':'soap',
                 'morebar': {
                             'bacon' : {
                                         'bla':'balbla'
                                       }
                             }
                },
                'bla'
                ]
     }
  
  print xpath_get(foo, "/morefoo/0/morebar/bacon")
  </code></pre>
  
  <p>[EDIT 2016] This question and the accepted answer are ancient. The newer answers may do the job better than the original answer. However I did not test them so I won't change the accepted answer.</p>