pylearner
pylearner

Reputation: 1460

Merge a dictionary and a list

Am trying to combine a dictionary and a list which has dictionaries and an empty dictionary

dict1 = {'a': 1, 'b': 2}
list1 = [{'c': 3}, {'d':4}]
emptydict = {}
emptylist = []

Trying to merge and make it a final dictionary which looks like below.

final = {'a': 1, 'b': 2, 'c': 3, 'd':4}

Code:

final = {**dict1, **list1[0], **list1[1], **emptydict, **emptylist} 

Here I dont know the length of list1, can anyone suggest me a better way than this ?

Upvotes: 1

Views: 104

Answers (2)

Bless
Bless

Reputation: 5370

If you are using python 3.3+, you can use ChainMap to merge list of dicts into a single dict. And then use ** operator to merge dict1 and dict(ChainMap(*list1)).

from collections import ChainMap

final = {**dict1, **ChainMap(*list1)}

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

dict.update updates an existing dictionary. Unfortunately it’s a mutating method that does not return a value. Therefore adapting it to functools.reduce requires a wrapper.

Due to this, I’d be tempted to use a good old loop:

final = dict(dict1)
for d in list1:
    final.update(d)

But for completeness, here’s a way using functools.reduce:

import functools

def dict_update(d, v):
    d.update(v)
    return d

final = functools.reduce(dict_update, list1, dict1.copy())

Upvotes: 5

Related Questions