def flatten()

in CWMetricsToOpenSearch/es_sink/transport_utils.py [0:0]


def flatten(current, key, result):
    '''Takes a path to an element in a nested dict (e.g., JSON) and recursively
       walks the whole tree, returning a 1-layer dict, with elements where the
       keys are the path elements joined with '_' and the values are the leaf
       values from the dict.
       flatten({'a': {'b':'c', 'd': 'e'}}, '', {}) =>
           {'a_b': 'c', 'a_d': 'e'}'''
    if isinstance(current, dict):
        for thiskey in current:
            valid_k = valid_key(str(thiskey))
            new_key = "{0}_{1}".format(key, valid_k) if len(key) > 0 else valid_k
            flatten(current[thiskey], new_key, result)
    else:
        result[key] = current
    return result