Skip to main content
HomeTutorialsPython

Python Dictionaries Tutorial

Learn how to create a dictionary in Python.
Jun 2020  · 3 min read

Dictionary is a built-in Python Data Structure that is mutable. It is similar in spirit to List, Set, and Tuples. However, it is not indexed by a sequence of numbers but indexed based on keys and can be understood as associative arrays. On an abstract level, it consists of a key with an associated value. In Python, the Dictionary represents the implementation of a hash-table.

What are Keys?

As shown in the figure below, keys are immutable ( which cannot be changed ) data types that can be either strings or numbers. However, a key can not be a mutable data type, for example, a list. Keys are unique within a Dictionary and can not be duplicated inside a Dictionary. If it is used more than once, subsequent entries will overwrite the previous value.

keys

Key connects with the value, hence, creating a map-like structure. For example, remove keys from the picture; all you are left with is a data structure containing a sequence of numbers. Dictionaries, therefore, hold a key: value pair at each position.

A Dictionary is represented by a pair of curly braces {} in which enclosed are the key: value pairs separated by a comma.

Creating a Dictionary

Syntax

As a refresher, here is a recipe for creating a Dictionary:

my_dict = {
  "key1":"value1",
  "key2":"value2"
}

In the above syntax, both the keys and the values are strings.

Example of Creating a Dictionary

pop = [30.55, 2.77, 39.21]

countries = ["afghanistan", "albania", "algeria"]

Let's convert the population data to a Dictionary. To create the Dictionary, you will use the curly brackets. Next, inside the brackets, you will have a bunch of key:value pairs. In this case, the keys are country names, and values are the corresponding populations.

The first key is Afghanistan, and its corresponding value is 30.55. Notice the colon that separates the key and value pair. Let's do the same for the other two key:value pairs and store the result in the variable world.

Now, to find the population for Albania, simply type world, and then the string Albania inside square brackets. In other words, you pass the key in square brackets and get the corresponding values.

world = {"afghanistan":30.55, "albania":2.77, "algeria":39.21}

world["albania"]
2.77

This approach is not only intuitive, but it is also very efficient because Python can look up these keys very fast, even for huge dictionaries.

Interactive Example of Creating a Dictionary

In the below example, you will use the strings in countries and capitals, create a Dictionary called europe with 4 key:value pairs. Here the countries will be the keys, and capitals will be the values. Beware of capitalization! Make sure you use lowercase characters everywhere. Finally, print out europe to see if the result is what you expected.

# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']

# From string in countries and capitals, create dictionary europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo'}

# Print europe
print(europe)

When you run the above code, it produces the following result:

{'norway': 'oslo', 'germany': 'berlin', 'france': 'paris', 'spain': 'madrid'}

Try it for yourself.

To learn more about dictionaries in Python, please see this video from our course Intermediate Python.

This content is taken from DataCamp’s Intermediate Python course by Hugo Bowne-Anderson.

Topics

Python Courses

Course

Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Writing Custom Context Managers in Python

Learn the advanced aspects of resource management in Python by mastering how to write custom context managers.
Bex Tuychiev's photo

Bex Tuychiev

tutorial

How to Convert a List to a String in Python

Learn how to convert a list to a string in Python in this quick tutorial.
Adel Nehme's photo

Adel Nehme

tutorial

A Comprehensive Tutorial on Optical Character Recognition (OCR) in Python With Pytesseract

Master the fundamentals of optical character recognition in OCR with PyTesseract and OpenCV.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Encapsulation in Python Object-Oriented Programming: A Comprehensive Guide

Learn the fundamentals of implementing encapsulation in Python object-oriented programming.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Python KeyError Exceptions and How to Fix Them

Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively.
Javier Canales Luna's photo

Javier Canales Luna

6 min

code-along

Full Stack Data Engineering with Python

In this session, you'll see a full data workflow using some LIGO gravitational wave data (no physics knowledge required). You'll see how to work with HDF5 files, clean and analyze time series data, and visualize the results.
Blenda Guedes's photo

Blenda Guedes

See MoreSee More