Introduction to python dictionaries

Introduction

Pamela Malondi
Dev Genius

--

Article cover image. Source: @emilep — https://unsplash.com/photos/xrVDYZRGdw4

One of the useful data structures in python is the dictionary. A python dictionary is similar to a list in that it is a collection of objects. Unlike a list, however, a dictionary is immutable and values are accessed through dictionary keys and not indexes. Other programming languages may refer to dictionaries as “associative arrays”. In this tutorial, you will learn to create your own dictionaries in python, how to access, add or remove elements from them, and the common built-in methods.

How to create a dictionary?

A dictionary holds key: value pairs and is created using curly braces “{}” with each key: value pair separated by a comma. Each key is mapped to an associated value. Values can be of any data type and can be duplicated. Keys on the other hand have to be unique and must be immutable.

#creating an empty dictionary 
my_dict = {}

Now it’s your turn to create your own empty dictionary. Open the python shell or create a new .py file in your favourite editor and type the following code.

Print out the type of my_dict in python shell. The output is <class ‘dict’>

The general syntax is as follows:

my_dict = {key1: value1, key2: value2, key3:value3, keyN: valueN}

To improve readability and minimize chances for introducing errors, the same code can be written as:

my_dict = {
key1: value1,
key2: value2,
key3: value3,
keyN: valueN,
}

Example

Now that you know how to create a dictionary, let’s now go over an example where we will create a telephone directory with the name and phone numbers of our friends.

telephone_directory = {
"Pam": "087655",
"Jane": "089655",
"Jim": "086495",
"Sandi": "08565",
"Elvis": "089690",
}

Accessing values of a dictionary

Let’s say you now want to check Sandi’s phone number, you will have to type the following command:

#print Sandi's phone number 
print(telephone_directory["Sandi"])
#output: 08565

We can use a for loop to print all the values in the directory:

for name, num in telephone_directory.items():
print(name,":",num)

See a screenshot of the code below:

telephone directory using a dictionary code screenshot

Output:

telephone directory output using a dictionary code screenshot

If we try accessing a value that does not exist in the dictionary, a KeyError message will be returned. Try typing the following code in your editor:

print(telephone_directory["Musa"])

Output:

KeyError output message when trying to access a value that does not exist in the dictionary

Another alternative way to access dictionary values is the get() method.

 #use the get method 
print(telephone_directory.get("Pam")
#Output: 087655

When trying to access a value that doesn’t exist with the get() method the program returns None instead of an error message.

#use get() to access invalid key 
print(telephone_directory.get("Musa")
#Output: None

The get() method allows you to specify a second argument to be printed instead of “None” if the key does not exist.

#specify message to be printed if key does not exist 
print(telephone_directory.get("Musa","Invalid key"))
#Output: Invalid Key

Checking the length of a dictionary

Checking the length of a dictionary is very simple:

dict_len = len(telephone_directory)
print(dict_len)
#Output: 5

Adding or changing dictionary elements

Unlike tuples, dictionaries are mutable, meaning you can add, change or delete the value of existing items in the dictionary.

# changing the value
print(telephone_directory)
telephone_directory["Pam"] = "097552"
print(telephone_directory)
#adding new name
telephone_directory["John"] = "0987654"
print(telephone_directory)

Output:

Removing elements from a dictionary

Removing elements from a dictionary is very easy using built-in methods. To remove a specific item from a dictionary, we can use the pop() method which removes the item for a given key and returns the value.

#remove element using pop() 
print(telephone_directory.pop("Jane"))
#Output: 089655

The popitem() method removes the last key-value pair item from the dictionary and returns it as a tuple:

#remove last item using popitem() method 
print(telephone_directory.popitem())
#Output: ('John', '0987654')

To remove all items at once you can use the clear() method:

#Delete all items in the dictionary 
telephone_directory.clear()
print(telephone_directory)
#Output: {}

Other dictionary methods

The following are built-in methods that you can use with dictionaries

  • copy(): returns a copy of the dictionary.
  • get(): returns the value of the specified key.
  • pop(): removes the element corresponding to the specified key.
  • popitem(): removes the last inserted element (value-key pair).
  • values: returns a list of all values.
  • items(): returns a list with a tuple for each key-value pair.
  • type(): returns variable type.
  • clear(): removes all elements from the dictionary.
  • str(): returns a string representation of the dictionary.
  • update(): updates dictionary with the key-value pair.

Learn more

Congratulations on reading till the end of the tutorial. You should now understand the basics of the dictionary data structure in python and should be able to create your own dictionary. Remember, the best way to learn is to practice. So get on with it!

--

--

Lifelong Learner. Working in FinTech. Business Intelligence. Loves Books. Instagram @malondireads | @i_coded_this