Author avatar

Gabriel Cánepa

Manipulating Lists and Dictionaries in Python

Gabriel Cánepa

  • Nov 26, 2018
  • 8 Min read
  • Nov 26, 2018
  • 8 Min read


Before we dive into our discussion about lists and dictionaries in Python, we’ll define both data structures. While we're at it, it may be helpful to think of them as daily to-do lists and ordinary school dictionaries, respectively.

  • A list is a mutable, ordered sequence of items. As such, it can be indexed, sliced, and changed. Each element can be accessed using its position in the list. The same applies to your agenda, where you can modify the order in which you do things and even reschedule a number of tasks for the next day if needed.

  • A dictionary is a mutable, unordered set of key-value pairs where each key must be unique. To access a given element, we must refer to it by using its key, much like you would look up a word in a school dictionary.

With these concepts in mind, let's review some of the available properties and methods of lists and dictionaries in Python. Although we do not intend to cover all of them, the following sections will give us a glimpse of what we can accomplish by using these data structures in this series.


In Python, dictionaries are written using curly brackets. Each key-value pair (also known as an element) is separated from the next with a comma. To illustrate, let's consider the following dictionary:

1    player = { 'firstName': 'Jabari', 'lastName': 'Parker', 'jersey': '2', 'heightMeters': '2.03', 'nbaDebutYear': '2014' }

where the keys are firstName, lastName, jersey, heightMeters, and nbaDebutYear. To access the value associated with any of them, we will use the following syntax:

1    player['firstName']
2    player['lastName']
3    player['jersey']
4    player['heightMeters']
5    player['nbaDebutYear']

Fig. 1 shows the output of the above statements:

Figure 1 - Accessing dictionary values through keys

However, if we attempt to access an element through a key that does not exist, we will run into a KeyError message. To address that scenario, we can use the .get() method. It takes a key as first argument and allows us to specify a fallback value if such key does not exist, as shown in Fig. 2:

1    player['weightKilograms']
2    player.get('weightKilograms', '0.0')

Figure 2 - Using the .get() method to prevent key errors

Of course, we can add that key and its corresponding value as a new element to the dictionary. To do that, we will use the .update() method as follows:

1    player.update({'weightKilograms': '111.1'})

Additionally, it is possible to update the value of a given key using an assignment operator:

1    player['jersey'] = '12'

Let's see in Fig. 3 what our dictionary now looks like:

1    print(player)

Figure 3 - Printing a dictionary

Dictionaries allow all kinds of data types as values, as we will learn towards the end of this guide, including lists and other dictionaries!


In Python, lists are written with square brackets. Although it can consist of different data types, a list will typically include only items of the same kind. In other words,

1    myList = [1, 'hello', 2.35, True]

is syntactically valid but not very useful, as you can imagine. On the other hand,

1    prices = [1.35, 2.99, 10.5, 0.66]

makes much more sense. To access any of the list elements, we can use its index:

1    prices[0]
2    prices[1]
3    prices[2]
4    prices[3]

Python lists are zero-indexed. Thus, the first element is at position 0, the second is at position 1, the third is at position 2, and so on. Also, the last item is considered to be at position -1.

The most common operation is to add a new element to the end of the list with the .append() method:

1    prices.append(3.49)

Likewise, it is also possible to insert an item at a given position (see Fig. 4):

1    prices.insert(2, 12.49)

Figure 4 - Creating a list and adding new elements

Another built-in method, .sort(), allows us to sort the items in the list either numerically, alphabetically, or by passing a custom function to the key parameter, as can be seen in Fig. 5. To illustrate, let's use prices and a new list called products:

1    prices.sort()
2    print(prices)
3    prices.sort(reverse=True)
4    print(prices)
5    products = ['Ball', 'Book', 'Chess set', 'Crayons', 'Doll', 'Play-Doh']
7    def product_len(product):
8        return len(product)
10    products.sort(key = product_len)
11    print(products)
12    products.sort(reverse = True, key = product_len)
13    print(products)

Figure 5 - Sorting lists

By default, .sort() operates in ascending order.

Lists can also be sliced, which means we can take portions (including the lower but not the upper limit) as shown in Fig. 6:

  • From the first element up to a given position: products[:3]

  • From a given position until the last element: products[2:]

  • Between two given positions in the list: products[2:4]

Figure 6 - Slicing lists

Putting It All Together

The real power of Python lists can be better appreciated when we use them to store more complex data structures than integers, floats, or strings. A list of dictionaries is a great example.

Let's create a few more dictionaries with information about other basketball players:

1new_player1 = { 'firstName': 'LaMarcus', 'lastName': 'Aldridge', 'jersey': '12', 'heightMeters': '2.11', 'nbaDebutYear': '2006', 'weightKilograms': '117.9'}
2new_player2 = { 'firstName': 'LeBron', 'lastName': 'James', 'jersey': '2', 'heightMeters': '2.03', 'nbaDebutYear': '2003', 'weightKilograms': '113.4' }
3new_player3 = { 'firstName': 'Kawhi', 'lastName': 'Leonard', 'jersey': '2', 'heightMeters': '2.01', 'nbaDebutYear': '2011', 'weightKilograms': '104.3' }

Now we can add these dictionaries, along with the one that we used in the first example of this guide, to a list called nba_players (which is empty at first):

1    nba_players = []
2    nba_players.append(player)
3    nba_players.append(new_player1)
4    nba_players.append(new_player2)
5    nba_players.append(new_player3)

Let's now inspect nba_players:

1    print(nba_players)

The entire list may not be easy to read, so the methods we described previously also apply in this case. Here are some examples:

  • Numbers of players in nba_players: len(nba_players)

  • First player in the list: nba_players[0]

  • The last two: nba_players[-2:]

  • Since each element in the list is a dictionary, we can access each player's NBA debut year and use it to sort the list (see Fig. 7):
1    def get_nba_debut_year(player):
2        return int(player['nbaDebutYear'])
4    nba_players.sort(key = get_nba_debut_year)
5    print(nba_players)

Figure 7 - Sorting a list of dictionaries


So where are lists and dictionaries used in the real world? Particularly, lists of dictionaries are what JSON (Javascript Object Notation) is made of. JSON is a popular text format for exchanging data and is used as the de facto standard in most APIs (Application Programming Interfaces) in all kind of environments and for a wide variety of purposes. The open NBA API, where we have taken the information used in this guide, is one such example.