How To Append A List To A Key In Dictionary Python

In this tutorial, we will learn how to append a list to a key in a dictionary in Python. In Python, dictionaries are mutable data structures that store key-value pairs. We can easily modify the values associated with keys, and in this case, we will append a list to the existing value associated with a specific key in the dictionary.

Step 1: Create a dictionary and a list

First, we need to create a dictionary and a list that we want to append to one of the key’s values in the dictionary.

Here, we have created a dictionary with keys ‘A’, ‘B’, and ‘C’ and their respective values as lists. We have also created a list my_list that we want to append to the value of the key ‘A’ in the dictionary my_dict.

Step 2: Check if the key exists in the dictionary

Before appending the list to the key, we must ensure that the key exists in the dictionary. We can use the in operator to check for the existence of the key in the dictionary.

This code checks if the key ‘A’ is present in the dictionary my_dict. It returns the output:

Key 'A' exists in the dictionary.

Step 3: Append the list to the key in the dictionary

Now that we know the key exists, we can append the list my_list to the value of the key ‘A’ in the dictionary my_dict.

Here, we have used the += operator which is equivalent to my_dict[key] = my_dict[key] + my_list.

Step 4: Display the modified dictionary

Finally, we can display the modified dictionary to observe how the list has been appended to the value of the key ‘A’.

The above code will display the following output:

Modified Dictionary:  {'A': [1, 2, 3, 10, 11, 12], 'B': [4, 5, 6], 'C': [7, 8, 9]}

As we can see, the list my_list has been appended to the value of the key ‘A’ in the dictionary my_dict.

Full Code

Conclusion

In this tutorial, we have learned how to append a list to a key in a dictionary in Python. We created a dictionary and a list, checked the existence of the key in the dictionary, appended the list to the key in the dictionary, and finally displayed the modified dictionary. This is a useful technique for manipulating and updating values in dictionaries in Python.