티스토리 뷰

반응형

How can I merge two Python dictionaries in a single expression?


For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.

In Python 3.5 or greater:

x = {'a':'1', 'b':'2', 'c':'3'} 
y = {'d':'4', 'e':'5', 'f':'6'} 
z = {**x, **y} 
print(z)
{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 'f': '6'}

Another example:

w = {'foo': 'bar', 'baz': 'qux', **y} # merge a dict with literal values
print(w)
{'foo': 'bar', 'baz': 'qux', 'd': '4', 'e': '5', 'f': '6'}

 

In Python 2, (or 3.4 or lower) write a function:

def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z

and

z = merge_two_dicts(x, y)

 

 

반응형
반응형
최근에 달린 댓글