Python Dictionary Append – 4 Best Ways to Add Key/Value Pairs

You can add multiple key-value pairs to a Python dictionary by using the update() method and passing a dictionary as an argument. For example, dict1.update(dict2) will insert all key-value pairs of dict2 into dict1.

age = {'Alice': 18}
age.update({'Bob': 23, 'Carl':45})
print(age)
# {'Alice': 18, 'Bob': 23, 'Carl': 45}

You can add a single key:value pair to a Python dictionary by using the square bracket approach dict[key] = value.

age = dict()
age['Alice'] = 42
print(age)
# {'Alice': 42}

In this article, we will look at how to append values to a dictionary in Python, so let’s start by clarifying what a Python dictionary actually is.

Dictionary Basics

Unlike other data types that only hold a single value as an element, a dictionary stores data values in key-value pairs, where the key is mapped to its associated value. Whilst the values of a dictionary can be of any type (even lists), the keys must be immutable, such as strings, numbers, or tuples.

In terms of syntax, a dictionary is defined by enclosing a comma-separated list of key-value pairs in curly brackets( i.e. { }). A colon (:) is used to separate each key from its associated value, and a comma (,) to separate each key/value pair. AΒ dictionary is defined as being ordered (as of Python v 3.7), changeable, and does not allow duplicates.

Let’s create a simple Python dictionary using a simple string, an integer, and a list as example values:

students={'name': 'John', 'age': 18, 'course': ['Maths']}
print(students)
# {'name': 'John', 'age': 18, 'course': ['Maths']}

So, now we have our sample dictionary let’s see how we can append, i.e., add, values to this.

Method 1: Square Brackets and Subscript Notation

To add an entire key/value pair to an existing dictionary, we can use the dictionary name followed by the key name in square brackets and then assign the associated value to it.

This is probably best illustrated by an example where we want to add the key β€˜surname’ and value β€˜Jones’ to our dictionary:

students['surname'] = 'Jones'
print(students)
# {'name': 'John', 'age': 18, 'course': ['Maths'], 'surname': 'Jones'}

If we have an existing key and we only want to update the associated value, we can do this as well with the square brackets method:

students['surname'] = 'Smith-Jones'
print(students)
# {'name': 'John', 'age': 18, 'course': ['Maths'], 'surname': 'Smith-Jones'}

With this method we can also use the β€˜+’ operator to append to an existing value.

For example, if we wanted to add a list item to the β€˜course’ key we could do so as follows:

students['course'] += ['Science']
print(students) 

{'name': 'John', 'age': 18, 'course': ['Maths', 'Science'], 'surname': 'Smith'}

Note that as we are adding a list item, it needs to be correctly formatted as such ([ ]).

Similarly, if we wanted to add a string to the β€˜surname’ key, to make it hyphenated, for example, we can do this too:

students['surname'] += '-Jones'
print(students)
# {'name': 'John', 'age': 18, 'course': ['Maths', 'Science'], 'surname': 'Smith-Jones'}

Method 2: dict.update()

Alternatively, we can use the built-in Python dictionary method, update(), to add new items to a specified dictionary. This method can be used to append multiple new key/value pairs if they do not already exist or to update an existing key with a new value.

Let’s start by looking at adding new key/pair values. In the example below, we are going to add the keys ’city’  and β€˜test_score’ to our dictionary along with their associated values:Β 

students.update({'city': 'London', 'test_score': 88.5})
print(students)
# {'name': 'John', 'age': 18, 'course': ['Maths', 'Science'], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

We can also use this method to update and replace only the value of an existing key in the dictionary rather than appending a whole new key/value pair:

students.update({'name': 'Bob'})
print(students)
# {'name': 'Bob', 'age': 18, 'course': ['Maths', 'Science'], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

Please bear in mind this method will overwrite any existing values, so we need to be careful when we use it. If we look at our β€˜course’ key, if we wanted to append (i.e., add) another subject, for example, β€˜English’ this method would not work:

students.update({'course': 'English'})
print(students)
# {'name': 'Bob', 'age': 18, 'course': 'English', 'surname': 'Smith', 'city': 'London', 'test_score': 88.5}

This was done to illustrate that the update() method overwrites rather than appends. Please note though for the remainder of the article we will assume that the β€˜course’ key contains the list ['Maths', 'Science'] as previously shown.

Method 3: append()

In addition to the built-in dictionary update() method, Python lists have a built-in append() method.

At this point, you may be wondering why the article didn’t start with this, as it should do exactly what we are trying to achieve.

πŸ’‘ Note: Whilst append() is certainly useful, be aware that this method only works if the key has already been defined and the value we are appending to is a list object.

This means that if we try to use the append() method on a string or integer value, Python will return an error:

students['name'].append('Henry')
print(students)

AttributeError: 'str' object has no attribute 'append'

However, if we now use this method on the β€˜course’ key, where the associated value is a list data type containing subjects, we get the following:

students['course'].append('English')
print(students)
# {'name': 'Bob', 'age': 18, 'course': ['Maths', 'Science', 'English'], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

So every time we call append() on an existing list within our dictionary, it adds a new item to the end (or right-hand side) of the list.

We can use this method to add any kind of object we want to a given list:

students['course'].append(5)
print(students)
# {'name': 'Bob', 'age': 18, 'course': ['Maths', 'Science', 'English', 5], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

Method 4: extend()

As we have seen the append() method can only be used when we want to add to an existing list value within our dictionary.

The extend() method takes it a step further and only works when we want to add a list to an existing list within our dictionary, i.e., we can not add integers, strings, or other data types.

For example, if we were looking to extend our ’course’ value (which is a list) with another subject, say β€˜French’, we would need to ensure this is specified as a list item:

students['course'].extend(['French'])
print(students)
# {'name': 'Bob', 'age': 18, 'course': ['Maths', 'Science', 'English', 5, 'French'], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

Whilst it is worth knowing this method exists, it is only relevant if we want to append list items to existing list items, so it has limited use. If we try to use extend() without a list item, e.g., a standard string object, it will attempt to convert the object to a list:

students['course'].extend('French')
print(students)
# {'name': 'Bob', 'age': 18, 'course': ['Maths', 'Science', 'English', 5, 'French', 'F', 'r', 'e', 'n', 'c', 'h'], 'surname': 'Smith-Jones', 'city': 'London', 'test_score': 88.5}

Summary

In this article, we have made some key assumptions with our aim of β€˜Appending Values to Dictionary in Python’. Namely that our definition of β€˜appending’ is basically to add and that the term β€˜values’ in our title refers to the value in the key/value pairing of a dictionary element.

We have not, therefore, looked at how to add keys only.

We have seen that there are various ways of appending values to an existing dictionary. Both the append() and extend() methods have limited use as they both need the associated values to be in a list, and as we have seen dictionaries can be of various data types.

The update() method overcomes this problem, but it will overwrite rather than β€˜append’ any existing values, so users should proceed cautiously.

The square brackets method, whilst arguably the most basic, seems to be the most flexible of all, as it allows us to add, update, and append values.

Programmer Humor

πŸ‘±β€β™€οΈ Programmer 1: We have a problem
πŸ§”β€β™‚οΈ Programmer 2: Let’s use RegEx!
πŸ‘±β€β™€οΈ Programmer 1: Now we have two problems

… yet – you can easily reduce the two problems to zero as you polish your “RegEx Superpower in Python“. πŸ™‚