Append value to an existing key in a Python dictionary

Python Dictionary

In this post, we are going to understand the dictionary append() method and How to Append value to an existing key in a Python dictionary.

Append() method

The append () method is used to append values to the existing key in the python dictionary. We need to search the key on which we want to append a value.

We will do this job by using following techniques.

  • Convert key type to list.
  • Define a dictionary with a key of list type
  • Define dictionary using collections.defaultdict(type)

1. Append value to an existing key by Convert a key to list type

We are defining a function val_append() with three arguments key, dictionary, value. We have the existing key ‘Students’ in the dict_sub, but it is not the key of the list type. We are checking first by using isinstance() method what is the type of key. If it is not the list type, We are converting it to the list type and appending the value to it.

Let us understand with example:

dict_sub = {'math':100,'Eng':100,'Chem':98,'students':'Jack'}
def val_append(dict_obj, key, value):
 if key in dict_sub:
  if not isinstance(dict_sub[key], list):
  # converting key to list type
   dict_sub[key] = [dict_sub[key]]
   # Append the key's value in list
   dict_sub[key].append(value)

#calling the function to append values
val_append(dict_sub,'students','mack')

print('after adding value to dictionary =\n',dict_sub)

Output

after adding value to the dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'students': ['Jack', 'mack']}

2. Append value to an existing key Define a dictionary with the key of list type

We define a dictionary that has a key ‘student’ type of list. This key does not initialize to any values, later we are appending the value in this key using the append() method.

dict_sub = {'math':100,'Eng':100,'Chem':98,'students':[]}

print('type of key =\n',type(dict_sub['students']))

dict_sub['students'].append('rack')

print('after adding value to dictionary =\n',dict_sub)

This is output after appending value ‘rack’ to ‘students’ key.We are checking the type of ‘students’ key,as it is showing it as list type.

Output

type of key =
 <class 'list'>
after adding value to dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'students': ['rack']}

3. Append a nested list of values to the existing dictionary’s key

In this code example, we are appending nested list to the key ‘student’ .

dict_sub = {'math':100,'Eng':100,'Chem':98,'students':[]}

print('type of key =\n',type(dict_sub['students']))

student_list = ['Tor','Sdney','Max','Sack']

dict_sub['students'].append(student_list)

print('after adding value to dictionary =\n',dict_sub)

This is output after appending nested list to ‘students’ key.

Output

type of key =
 <class 'list'>
after adding value to dictionary =
 {'math': 100, 'Eng': 100, 'Chem': 98, 'students': [['Tor', 'Sdney', 'Max', 'Sack']]}

4.Append value to an existing key to a dictionary of collections.defaultdict(type)

The defaultdict is defined in the collection module, which is a subclass of dict class, and initialize with a function, its functionality is almost the same as a dictionary. The defaultdict does not raise a keyError, because it initializes a dictionary that has default values for nonexistence key.

The type of values is decided based on the type passed as an argument. Defaultdict has a list, set, int for values type. So in the DefaultDict the existence of a key is not required.

How does it work?

In this code example, we are creating a defaultdict dictionary that can have values of list type. Because values type is decided based on datatype we pass while initializing the dictionary.

Now we are appending values to list type values using append() method,We have appended two values in students key.

from collections import defaultdict
dict_sub = defaultdict(list)
dict_sub['students'].append('rack')
dict_sub['students'].append('Jack')
print('after adding value to dictionary =\n',dict_sub)

This is output after appending two values ‘rack’,’jack’ to ‘students’ key.

Output

after adding value to dictionary =
 defaultdict(<class 'list'>, {'students': ['rack', 'Jack']})

Conclusion:

We have understood the appended values to an existing key in a Python dictionary by using the append() method. So by using this method we can easily add values to an existing key or append the nested values list to the existing key.

Happy Learning !!