Cascade get value from dictionary in Python
Several times I’ve been faced with the problem:
Get a value from a dictionary. If the key is not present, then get from another key.
Normally, the implementation would go like this:
Or, even worse, with try-catch statements. That’s fine if the sequence is fixed, but what if you want to have some flexibility? Well, my solution is like this:
def cascade_get_value(entry, array, final = None):
Try to get a value from a dict by iterating through a list of keys.
@param entry: a dictionary
@param array: the list of keys
@param final: the default value
It returns the value of the first matching key, or the value specified
in the "final" argument if no matches have been found.
result = None
for val in array:
result = entry.get(val, None)
if not result:
result = final
Pretty, isn’t it?
Note: This is a post transferred from Laurii for historical and consolidation purposes.
A little experiment: If you find this post and ad below useful, please check the ad out :-)