티스토리 뷰
반응형
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)
반응형
'Devolopment > Python' 카테고리의 다른 글
PDF to TEXT by Python3 (0) | 2021.05.10 |
---|---|
STRIP TAGS AND JAVASCRIPT FROM HTML PAGE, LEAVING ONLY SAFE TAGS (PYTHON RECIPE) (0) | 2020.03.17 |
Python으로 만든 데몬을 시작/중지/재시작 시키는 쉘스크립트 예제. (0) | 2020.03.02 |
PyQt5 에서 UI File 불러오는 방법 (0) | 2020.02.25 |
Python 3.x 에서 Dictionary 정렬하기 (0) | 2020.02.25 |
반응형
최근에 달린 댓글