Thursday, January 23, 2025
HomeProgrammingAppend a Dictionary to a Dictionary

Append a Dictionary to a Dictionary

To append a dictionary to another dictionary in Python, you can use the update() method or dictionary unpacking.

Using update():

python
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)

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

Using Dictionary Unpacking (Python 3.5+):

python
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1 = {**dict1, **dict2}
print(dict1)

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

Both approaches add the key-value pairs from dict2 to dict1.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x