Skip to content

Instantly share code, notes, and snippets.

@jkeyes
Created May 15, 2010 22:11
Show Gist options
  • Save jkeyes/402439 to your computer and use it in GitHub Desktop.
Save jkeyes/402439 to your computer and use it in GitHub Desktop.
context = {
'database': {
'port': 9990,
'users': ['number2', 'dr_evil']
},
'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'],
'domain.name': 'virtucon.com'
}
# Most comprehensive solution by http://stackoverflow.com/users/95810/alex-martelli
# See more about this problem at http://stackoverflow.com/questions/2841971/compound-dictionary-keys
def getitem(context, key):
stk = [(key.split('.'), context)]
while stk:
kl, ctx = stk.pop()
if not kl: return ctx
if kl[0].isdigit():
ik = int(kl[0])
try: stk.append((kl[1:], ctx[ik]))
except LookupError: pass
for i in range(1, len(kl) + 1):
k = '.'.join(kl[:i])
if k in ctx: stk.append((kl[i:], ctx[k]))
raise KeyError(key)
if __name__ == "__main__":
print getitem(context, 'database')
print getitem(context, 'database.port')
print getitem(context, 'database.users.0')
print getitem(context, 'admins')
print getitem(context, 'domain.name')
try:
getitem(context, 'database.nosuchkey')
except KeyError, e:
print "Error:", e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment