Skip to content

Instantly share code, notes, and snippets.

@bagyr
Created March 23, 2012 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagyr/c454616b6168892b1aba to your computer and use it in GitHub Desktop.
Save bagyr/c454616b6168892b1aba to your computer and use it in GitHub Desktop.
Xpath for python dict
def editByXpath(dict, path, val):
try:
if path[0].isdigit():
p = int(path[0])
else:
p = path[0]
if len(path) == 1:
dict[p] = val
return
else:
editByXpath(dict[p], path[1:], val)
except:
raise KeyError()
foo = {
'spam':'eggs',
'morefoo': [{
'bar':'soap',
'morebar': {
'bacon' : 'narhwall'
}
},
'bla'
]
}
editByXpath(foo, ['morefoo', '0', 'morebar', 'bacon'], 'zlo')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment