Skip to content

Instantly share code, notes, and snippets.

@dedeibel
Last active December 19, 2016 13:21
Show Gist options
  • Save dedeibel/a5818aa546e5c135d116ead2b1d1b439 to your computer and use it in GitHub Desktop.
Save dedeibel/a5818aa546e5c135d116ead2b1d1b439 to your computer and use it in GitHub Desktop.
python get with nested structures and default
def mget(dic, *keys):
ret = dic
last_key = keys[-1]
for key in keys[:-1]:
ret = ret.get(key, {})
return ret[last_key]
def mgetd(dic, *keys):
ret = dic
last_key = keys[-2]
last_default = keys[-1]
for key in keys[:-2]:
ret = ret.get(key, {})
return ret.get(last_key, last_default)
d = {
'my': {
'nested': {
'ds': {
'value': 'jackpot',
},
'value': 'val1',
},
'value2': 'val2',
},
}
print 'jackpot: '+ str(mget(d, 'my', 'nested', 'ds', 'value'))
print 'value : '+ str(mget(d, 'my', 'nested', 'value'))
print 'value2 : '+ str(mget(d, 'my', 'value2'))
try:
print 'empty : '+ str(mget(d, 'my', 'nested', 'ds', 'fail'))
except Exception as x:
print x
try:
print 'empty : '+ str(mget(d, 'my', 'fail'))
except Exception as x:
print x
try:
print 'empty : '+ str(mget(d, 'my', 'nested', 'fail'))
except Exception as x:
print x
try:
print 'empty : '+ str(mget(d, 'my', 'fail', 'fail'))
except Exception as x:
print x
print 'd jackpot: '+ str(mgetd(d, 'my', 'nested', 'ds', 'value', 'default'))
print 'd value : '+ str(mgetd(d, 'my', 'nested', 'value', 'default'))
print 'd value2 : '+ str(mgetd(d, 'my', 'value2', 'default'))
print 'd empty : '+ str(mgetd(d, 'my', 'nested', 'ds', 'fail', 'default'))
print 'd empty : '+ str(mgetd(d, 'my', 'fail', 'default'))
print 'd empty : '+ str(mgetd(d, 'my', 'nested', 'fail', 'default'))
print 'd empty : '+ str(mgetd(d, 'my', 'fail', 'fail', 'default'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment