CommonLounge Archive

Python 3: Dictionaries and Tuples

March 22, 2019

In this tutorial, we will learn about two more data types: dictionaries and tuples.

Dictionaries

A dictionary is similar to a list, but you access values by looking up a key instead of a numeric index. Let’s look at what a dictionary looks like:

A key can be any string or number. Here, the keys are ‘a’, ‘o’, and ‘g’. The corresponding values are ‘alpha’, ‘omega’, and ‘gamma’. Next, let’s look at how we will define this dictionary in code:

greek_alphabets_dict = {
    'a': 'alpha', 
    'o': 'omega', 
    'g': 'gamma'
}
print(greek_alphabets_dict)

The values corresponding to the keys in the dictionary can be anything — including other objects like lists. Let’s look at an example:

participant = {
    'name': 'CommonLounge', 
    'country': 'Canada', 
    'favorite_numbers': [7, 42, 92]
}

With this command, you just created a variable named participant with three key–value pairs:

  • The key 'name' points to the value 'CommonLounge' (a string object),
  • 'country' points to 'Canada' (another string),
  • and 'favorite_numbers' points to [7, 42, 92] (a list with three numbers in it).

The syntax to define an empty dictionary is:

x = {}
print(x)
# Output: {}

This shows that you just created an empty dictionary.

Accessing keys of a dictionary

You can access the content of individual keys with the [] syntax:

print(participant['name'])
# Output: CommonLounge

See, it’s similar to a list. But you don’t need to remember the index – just the name.

What happens if we ask Python the value of a key that doesn’t exist? Can you guess? Let’s try it and see!

print(participant['age'])

Output:

Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'age'

Look, another error! This one is a KeyError. Python is helpful and tells you that the key 'age' doesn’t exist in this dictionary.

Dictionaries vs lists

When should you use a dictionary or a list? Well, that’s a good point to ponder. Just have a solution in mind before looking at the answer in the next line.

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

Adding key-value pairs

Dictionaries, like lists, are mutable, meaning that they can be changed after they are created. You can add new key–value pairs to a dictionary after it is created, like this:

participant['favorite_language'] = 'Python'
print(participant)
# Output: {'country': 'Canada', 
#   'favorite_language': 'Python', 
#   'favorite_numbers': [7, 42, 92],
#   'name': 'Commonlounge'}

Changing value for a key

You can also change a value associated with an already-created key in the dictionary. Type this:

participant['country'] = 'Germany'
print(participant)
# Output: {'country': 'Germany', 
#   'favorite_language': 'Python', 
#   'name': 'Commonlounge'}

As you can see, the value of the key 'country' has been altered from 'Canada' to 'Germany'.

Finding number of key value pairs

Like lists, using the len() method on the dictionaries returns the number of key–value pairs in the dictionary. Go ahead and type in this command:

print(len(participant))
# Output: 4

Deleting items using pop()

You can use the pop() method to delete an item in the dictionary. Say, if you want to delete the entry corresponding to the key 'favorite_numbers', just type in the following command:

participant.pop('favorite_numbers')
print(participant)
# Output: {'country': 'Canada', 
#   'favorite_language': 'Python', 
#   'name': 'Commonlounge'}

As you can see from the output, the key–value pair corresponding to the favorite_numbers key has been deleted.

Nested dictionaries

Dictionaries can also be nested — consider the example below:

country = {
   'name': 'Canada', 
   'prime_minister': {
       'name': 'Justin Trudeau',
       'place_of_birth': 'Ontario, Canada'
   }
}
print(country['prime_minister']['name']) 
# Output: 'Justin Trudeau'

There’s more we can do with Python dictionaries, and we’ll be learning about it later in the course in the following tutorial: Python3 Dictionaries.

Iterating over dictionaries

Next, let’s learn how to use a for-loop to iterate over a dictionary’s keys.

Remember the following dictionary from above?

greek_alphabet_dict = {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
## By default, iterating over a dict iterates over its keys.
## Note that the keys are in a random order, so you may see a different order printed
for key in greek_alphabet_dict:
    print(key)  ## prints a g o (in some order)

Thus, the for...in loop lets us access the keys of the dictionary. Note that the keys will appear in a random order.

Next, let’s look at more ways to do the same. The methods dict.keys() and dict.values() return lists of the keys or values explicitly.

greek_alphabet_dict = {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
for key in greek_alphabet_dict.keys():
    print(key)  ## prints a g o (in some order)
## Get the .keys() list:
print(greek_alphabet_dict.keys())  ## ['a', 'o', 'g']
## Likewise, there's a .values() list of values
print(greek_alphabet_dict.values())  ## ['alpha', 'omega', 'gamma']

Note: dict.keys(), dict.values(), etc don’t actually construct a list immediately. They return something called a generator, which is like a lazy list. If you go over over the entire result, a generator behaves like a list. But if you iterate over only the first few elements (or call dict.keys() but don’t do anything with it), then we can avoid the cost of constructing the whole list — a performance win if the data is huge.

Tuples

A tuple is a fixed-size group of elements. A common use of tuples is to represent pairs, triplets, or larger groups of values. For example, if you wanted to represent (x, y) coordinates of a map in Python, tuples would be a good idea.

To create a tuple, just list the values within parentheses separated by commas. The “empty” tuple is just an empty pair of parenthesis. Accessing the elements in a tuple is just like a list — len(), [ ], for, in, etc. all work the same.

t = (1, 2, 'hi')
print(len(t))       ## 3
print(t[2])         ## hi

Tuples are like lists, except they cannot be changed. The technical term for this is — tuples are immutable.

t = (1, 2, 'hi')
print(t)
#t[2] = 'bye'       ## NO, tuples cannot be changed
t = (1, 2, 'bye')   ## this works (creates new tuple)
print(t)

Tuples are a convenient way to pass around a little logical, fixed size bundle of values. For example, if we wanted to have a list of 3d coordinates, the natural Python representation would be a list of tuples, where each tuple of size 3 is holding one (x, y, z) group.

To create a size-1 tuple, the lone element must be followed by a comma.

t = ('hi',)   ## size-1 tuple
print(t)

It’s a funny case in the syntax, but the comma is necessary to distinguish the tuple from the ordinary case of putting an expression in parentheses.


Assigning a tuple to an identically sized tuple of variable names assigns all the corresponding values. If the tuples are not the same size, it throws an error. (This feature works for lists too.)

(x, y, z) = (42, 13, "hike")
print(z)  ## hike

Getting tuples of key-value pairs from a dictionary

Remember we were looking at methods of a dictionary like .keys(), .values() etc?There’s also an items() method which returns a list of (key, value) tuples, which is the most efficient way to examine all the key-value data in the dictionary.

greek_alphabet_dict = {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
## .items() is the dict expressed as (key, value) tuples
print(greek_alphabet_dict.items())  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
## This loop syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in greek_alphabet_dict.items(): print(k, '==>', v)
## a ==> alpha    
## o ==> omega     
## g ==> gamma

It’s also fairly common to pass these methods to the sorted() function to iterate over keys / values / items in sorted order. For example:

greek_alphabet_dict = {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
## Common case -- loop over the keys in sorted order,
## accessing each key/value
for key in sorted(greek_alphabet_dict.keys()):
    print(key, greek_alphabet_dict[key])

Summary

Awesome! In this tutorial, you learned about:

  • dictionaries — objects stored as key–value pairs
  • Operations on dictionaries — accessing, adding keys, removing keys, updating values
  • Nested dictionaries — dictionaries as values in another dictionary
  • Iteration over dictionaries — how to go over all the key/value pairs
  • tuples - fixed size bundle of values which are immutable

Excited for the next part?

Based on content from https://tutorial.djangogirls.org/en/python_introduction/


© 2016-2022. All rights reserved.