pythonlistdictionary

How do I merge a list of dicts into a single dict?


How can I turn a list of dicts like [{'a':1}, {'b':2}, {'c':1}, {'d':2}], into a single dict like {'a':1, 'b':2, 'c':1, 'd':2}?


Answers here will overwrite keys that match between two of the input dicts, because a dict cannot have duplicate keys. If you want to collect multiple values from matching keys, see How to merge dicts, collecting values from matching keys?.


Solution

  • This works for dictionaries of any length:

    >>> result = {}
    >>> for d in L:
    ...    result.update(d)
    ... 
    >>> result
    {'a':1,'c':1,'b':2,'d':2}
    

    As a comprehension:

    # Python >= 2.7
    {k: v for d in L for k, v in d.items()}
    
    # Python < 2.7
    dict(pair for d in L for pair in d.items())