How to Append an Element to a Key in a Dictionary in Python

To append an element to a dictionary key in Python, use the collections.defaultdict() function. Supply the default key data type as the first argument of the function, and when elements are appended to the dictionary they will be of the data type you have chosen.


Let's demonstrate this by setting the default dictionary type to list then append an element to a key.


import collections

dictionary = collections.defaultdict(list)

defaultdict(<class 'list'>, {'a': ['hi']})


Note – you will need to import the Python collections module before you can use the collections class.