Table of Contents

How to Merge more than two python dictionaries

how to merge dictionaries in python

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

merge two or more dictonaries using **kwargs

dict3 = {"d":4 , "e":6}

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

How to append to python dictionary by key

#to append Use different type defultdict
from collections import defaultdict

dictnew = defaultdict(list)
dictnew = {"a" : [1,2]}
print(dictnew)
{'a': [1, 2]}

#now lets append
dictnew['a'].append(3)
dictnew
{'a': [1, 2, 3]}

Related Posts

1