Working with Dictionaries in Python

Understanding how to create and manipulate dictionaries in Python.

Giulio Laurenti, PhD
Geek Culture

--

Photo by Ivo Rainha on Unsplash

Dictionaries are one of the built-in data structures in Python. They are mutable collections of keyvalue pairs.

Mutable means that we can modify a dictionary by adding, removing or changing elements.

In this post, we will learn to create and manipulate dictionaries.

Creating dictionaries
Dictionaries can be created by using curly braces {} to contain pairs of key — value elements. The key and value must be separated by a column, while the different key—value pairs by commas.

# Create a dictionary that contains the names of employees ad their role.

employees = {"Mark" : "Scientist", "Jane" : "Manager", "John" : "Data Analyst"}

print(employees)
{'Mark': 'Scientist', 'Jane': 'Manager', 'John': 'Data Analyst'}

Keys can also refer to lists of values.

# Create a dictionary with departments and employees in them.

departments = {"R&D" : ["Peter", "Jasmine", "Laura"], "HR" : ["Jake", "Lizzie"]}

print(departments)
{'R&D': ['Peter', 'Jasmine', 'Laura'], 'HR': ['Jake', 'Lizzie']}

Keys can be numbers.

# Create a dictionary with ID number and name of…

--

--

Giulio Laurenti, PhD
Geek Culture

A Molecular Biologist who enjoys writing about programming, science, and the wonderful world around us.