How can I combine dictionaries with the same keys?

前端 未结 5 485
渐次进展
渐次进展 2020-12-01 17:35

I have a list of dictionaries like so:

dicts = [
    {\'key_a\': valuex1,
     \'key_b\': valuex2,
     \'key_c\': valuex3},

    {\'key_a\': valuey1,
     \         


        
5条回答
  •  鱼传尺愫
    2020-12-01 17:45

    You can merge dictionaries in the following way:

    def merge_dicts(dict_list, separator=''):
        """
        Merges list of dictionaries to a single dictionary, Concatenates values with the same key.
        :param dict_list: list of dictionaries to be merged.
        :param separator: separator to be inserted between values of same key.
        :return: Merged dictionary.
        """
        return {k1: separator.join([d[k1] for d in dict_list if k1 in d])
                for k1 in set(reduce(lambda x, y: x+y, [k.keys() for k in dict_list]))
        }
    

提交回复
热议问题