Skip to content

Cascade get value from dictionary in Python

May 31st, 2016 - SoftwareTutorial(1 min)

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:

if dict.has_key(key1):
    return dict[key1]
elif dict.has_key(key2):
    return dict[key2]
...
else:
    return default_value

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 result:
            break
    if not result:
        result = final

    return result

Pretty, isn’t it?

Note: This is a post transferred from Laurii for historical and consolidation purposes.

Share on
Reddit
Linked in
Whatsapp

A little experiment: