Compound dictionary keys
Posted
by John Keyes
on Stack Overflow
See other posts from Stack Overflow
or by John Keyes
Published on 2010-05-15T22:27:06Z
Indexed on
2010/05/15
22:40 UTC
Read the original article
Hit count: 358
I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it?
context = {
'database': {
'port': 9990,
'users': ['number2', 'dr_evil']
},
'admins': ['[email protected]', '[email protected]'],
'domain.name': 'virtucon.com'
}
def getitem(key, context):
if hasattr(key, 'upper') and key in context:
return context[key]
keys = key if hasattr(key, 'pop') else key.split('.')
k = keys.pop(0)
if keys:
try:
return getitem(keys, context[k])
except KeyError, e:
raise KeyError(key)
if hasattr(context, 'count'):
k = int(k)
return context[k]
if __name__ == "__main__":
print getitem('database', context)
print getitem('database.port', context)
print getitem('database.users.0', context)
print getitem('admins', context)
print getitem('domain.name', context)
try:
getitem('database.nosuchkey', context)
except KeyError, e:
print "Error:", e
Thanks.
© Stack Overflow or respective owner