Merge two dictionaries and keep the values for duplicate keys in Python

前端 未结 8 2302
广开言路
广开言路 2021-02-08 19:16

Let\'s suppose that I have two dictionaries:

dic1 =  { \"first\":1, \"second\":4, \"third\":8} 
dic2 =  { \"first\":9, \"second\":5, \"fourth\":3}
8条回答
  •  情深已故
    2021-02-08 19:57

    Here's a naive solution; copy one of the dictionaries over to the result and iterate over the other dictionary's keys and values, adding lists to the result as necessary. Since there are only two dictionaries, no merged list will have more than 2 items.

    dic1 = {"first": 1, "second": 4, "third": 8} 
    dic2 = {"first": 9, "second": 5, "fourth": 3}
    dic3 = dict(dic2)
    
    for k, v in dic1.items():
        dic3[k] = [dic3[k], v] if k in dic3 else v
    
    print(dic3) # => {'first': [9, 1], 'second': [5, 4], 'fourth': 3, 'third': 8}
    

    If you'd like single values to be lists (likely better design; mixed types aren't much fun to deal with) you can use:

    dic3 = {k: [v] for k, v in dic2.items()}
    
    for k, v in dic1.items():
        dic3[k] = dic3[k] + [v] if k in dic3 else [v]
    
    print(dic3) # => {'first': [9, 1], 'second': [5, 4], 'fourth': [3], 'third': [8]}
    

    Generalizing it to any number of dictionaries:

    def merge_dicts(*dicts):
        """
        >>> merge_dicts({"a": 2}, {"b": 4, "a": 3}, {"a": 1})
        {'a': [2, 3, 1], 'b': [4]}
        """
        merged = {}
        
        for d in dicts:
            for k, v in d.items():
                if k not in merged:
                    merged[k] = []
    
                merged[k].append(v)
        
        return merged
    

    You can use collections.defaultdict to clean it up a bit if you don't mind the import:

    from collections import defaultdict
    
    def merge_dicts(*dicts):
        """
        >>> merge_dicts({"a": 2}, {"b": 4, "a": 3}, {"a": 1})
        defaultdict(, {'a': [2, 3, 1], 'b': [4]})
        """
        merged = defaultdict(list)
        
        for d in dicts:
            for k, v in d.items():
                merged[k].append(v)
        
        return merged
    

提交回复
热议问题