def flatten(d):
    """Recursively flatten a dictionary of varying depth,
    putting all keys at a single level.
    """
    flatd = {}
    for k, v in d.items():
        if isinstance(v, dict):
            flatd.update(flatten(v))
        else:
            flatd[k] = v
    return flatd