Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Manipulating Lists and Dictionaries in Python

Nov 26, 2018 • 8 Minute Read

Introduction

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.

Dictionaries

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:

      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:

      player['firstName']
    player['lastName']
    player['jersey']
    player['heightMeters']
    player['nbaDebutYear']
    

Fig. 1 shows the output of the above statements:

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:

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

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:

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

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

      player['jersey'] = '12'
    

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

      print(player)
    

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

Lists

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,

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

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

      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:

      prices[0]
    prices[1]
    prices[2]
    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:

      prices.append(3.49)
    

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

      prices.insert(2, 12.49)
    

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:

      prices.sort()
    print(prices)
    prices.sort(reverse=True)
    print(prices)
    products = ['Ball', 'Book', 'Chess set', 'Crayons', 'Doll', 'Play-Doh']
        
    def product_len(product):
        return len(product)

    products.sort(key = product_len)
    print(products)
    products.sort(reverse = True, key = product_len)
    print(products)
    

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]

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:

      new_player1 = { 'firstName': 'LaMarcus', 'lastName': 'Aldridge', 'jersey': '12', 'heightMeters': '2.11', 'nbaDebutYear': '2006', 'weightKilograms': '117.9'}
new_player2 = { 'firstName': 'LeBron', 'lastName': 'James', 'jersey': '2', 'heightMeters': '2.03', 'nbaDebutYear': '2003', 'weightKilograms': '113.4' }
new_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):

      nba_players = []
    nba_players.append(player)
    nba_players.append(new_player1)
    nba_players.append(new_player2)
    nba_players.append(new_player3)
    

Let's now inspect nba_players:

      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):

      def get_nba_debut_year(player):
        return int(player['nbaDebutYear'])
        
    nba_players.sort(key = get_nba_debut_year)
    print(nba_players)
    

Summary

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.

Gabriel Cánepa

Gabriel C.

Written Content Author

More about this author