import json


def save_dict_to_json_file(data, filename):
    """ merge a list of Python dictionaries into one dictionary
        and save the dictionary to a JSON file
        If same key exists in data(dicts) which will be merged,
        the key will be overridden.

        Args:
            data (`list`): list of dictionaries
            filename (`string`): filename to save
        Raise:
            Exception
        Returns:
            output (`dict`): Python dictionary

        Example:

        >>> dev.api.save_dict_to_file(data=[dict1, dict2], 'merged_dict')
        {
            'a': {        # came from `dict1`
                'b': 1,
            },
            'c': {        # came from `dict2`
                'd': 2,
            }
        }

    """
    if isinstance(data, list):
        output = {}
        for dict_ in data:
            if isinstance(dict_, dict):
                output.update(dict_)
            else:
                raise Exception(
                    '{dict_} is not dictionary.'.format(dict_=dict_))
        with open(filename, 'w+') as f:
            f.write(json.dumps(output))
    else:
        raise Exception('`data` {data} is not list.'.format(data=data))

    return output