There are times when you do several indirections in a dictionary. That is, the key is also a dictionary with a key which also a dictionary like this:
>>> c['x'] = 'y'
>>> b['y'] = 'z'
>>> a['z'] = [1, 2, 3]
>>> a[b[c['x']]]
[1, 2, 3]
However, you don't want it throwing exception when the innermost key do not exists. In the example above, the innermost key is 'x' in c['x'], and instead of throwing an exception, you want it to return an empty list. This is what you do using 'get' method in dict:
>>> r = a.get(b.get(c.get('x','nothing here'),'nothing here'),[])
>>> r
[1, 2, 3]
>>> r = a.get(b.get(c.get('xx','nothing here'),'nothing here'),[])
>>> r
[]
'nothing here' should not match any keys for this to work. Starting at the innermost dict, 'xx' key does not exist in c, so, it returns 'nothing here' which also do not exist in b and therefore returned also 'nothing here', and finally, since 'nothing here' key does not exist in a, it returned an empty list.
A similar scenario might happen for a dict of a dict of a dict like this:
>>> u = {}
>>> u['xxx'] = {}
>>> u['xxx']['yyy'] = {}
>>> u['xxx']['yyy']['zzz'] = [2, 3,4]
Instead of throwing an exception if no such key exist in this dict, you just want it to return an empty list. Here is the way to do it.
>>> u.get('xxx',{}).get('yyy',{}).get('zzz',[])
[2, 3, 4]
>>> u.get('xxx',{}).get('yyy',{}).get('ooo',[])
[]
>>> u.get('xxx',{}).get('ooo',{}).get('zzz',[])
[]
>>> u.get('ooo',{}).get('yyy',{}).get('zzz',[])
[]
>>> u.get('ooo',{}).get('ooo',{}).get('zzz',[])
[]
>>> u.get('ooo',{}).get('ooo',{}).get('ooo',[])
[]
Ultimately, the default value at the last 'get' is the one that will be returned when any of the 3 keys do not exists in the dict. The first instance of get must return an empty dict because the 'get' method will be applied against it. Try using an empty list on that 'get' to see what I mean.
No comments:
Post a Comment