Append dictionary values to list Python

In this article we are going to look at how to append values to a dictionary in Python, so lets start by clarifying what a Python dictionary actually is.

Table of Contents

  • Dictionary Basics
  • Method 1: Square Brackets and Subscript Notation
  • Method 2: dict.update()
  • Method 3: append()
  • Method 4: extend()
  • Summary

Dictionary Basics

Unlike other data types that only hold a single value as an element, a dictionary is used to store 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, 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.

Lets 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 lets 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.

Lets 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 update() method, Python also has a built-in append() method. At this point, you may be wondering why the article didnt start with this, as it should do exactly what we are trying to achieve. Whilst append() is certainly useful, the important thing to be aware of, is 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 are looking to add to an existing list value within our dictionary. The extend() method takes it a step further and only works when we are looking 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 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 with caution.

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.

Video liên quan

Chủ đề