Categories
Beginner education Python

Demystifying Python Dictionaries

A guide for new coders

Photo by Stas Knop on Pexels.com

If you know how to use a regular dictionary, you know how to use a Python dictionary. (Well, sort of.)

In a regular dictionary, you look up a word to find its definition. In a Python dictionary, you look up a “key” (a word) to find its associated “value” (its definition). Together, we call these “key-value pairs”.

So what’s a Python dictionary?

A Python dictionary is essentially a collection of data (i.e., key-value pairs) organized in an associative array.

Dictionaries can store all kinds of information — from numbers and strings to lists and sets (and even other dictionaries). This, combined with the amount of data they can contain, makes dictionaries great for working with mixed data types.

Here’s the basic format of a dictionary:

dictionary_name = {key1 : [value1, value2],
                   key2 : [value3, value4],
                   key3 : [value5, value6]}

For example: Let’s say we have a list of professors and the courses they teach, and we want to create a dictionary using that data.

Here’s the information that will go in our dictionary:

*** PROFESSOR COURSE ASSIGNMENTS ***

Professor Smith teaches ENGS 002 and ENGS 201
Professor Rasgotra teaches SPAN 101 and SPAN 205
Professor Zhang teaches GEOG 002 and ENVS 281
Professor Martinez teaches MATH 051, MATH 052, and STAT 110

Here are the steps we will take to complete this dictionary:

  1. Create a dictionary
  2. Add data to / edit data in the dictionary

1. Let’s Create a Dictionary

To create an empty dictionary:

a) use empty brackets {}, or b) use the dict() method:

#a) Creating an empty dictionary using brackets:
my_dictionary = {}

#b) Creating an empty dictionary using the dict() method:
my_dictionary = dict()

Both of these statements will create an empty dictionary called ‘my_dictionary’.

To create a dictionary and and add data to it at the same time:

a) use brackets {} containing the data, or b) the dict() method containing the data:

#a) Creating a dictionary with brackets {data included}
my_dictionary = {key1 : value1, key2 : value2, key3 : value3}

#b) Creating a dictionary using the dict() method (data included)
my_dictionary = dict(key1 = value1, key2 = value2, key3 = value3)

Both of these statements will create this dictionary:

my_dictionary = {key1 : value1,
                 key2 : value2,
                 key3 : value3}

Since we already know some of the information we want to include in our dictionary, let’s create a dictionary with that data using brackets.

professors = {'Smith' : ['ENGS 002', 'ENGS 201'],
              'Rasgotra' : ['SPAN 101', 'SPAN 205'],
              'Zhang' : ['GEOL 002', 'ENVS 281'],
              'Martinez' : ['MATH 051', 'MATH 052', 'STAT 110']}

2. Okay, We’ve Created Our Dictionary — Now Let’s Edit It

Let’s say we want to update the dictionary to reflect the following changes:

  • A new professor, Professor Harris, just started teaching HLTH 101, HLTH 102, and HLTH 110.
  • Professor Rasgotra is now teaching a third course: SPAN 001.

Adding a New Key-Value Pair

Professor Harris is teaching this semester, so let’s add her to the dictionary. This means we want to add the new key, ‘Harris’, and its associated value, [‘HLTH 101’, ‘HLTH 102’, ‘HLTH 110’].

The general format for adding a new value-pair to a Python dictionary is:

dictionary_name[key] = [value1, value2, value3]

Keys are immutable, which means that, once created, they can’t be changed. While keys can be any immutable data type (e.g., tuples, strings, etc), values are mutable, and can be any data type.

Here’s how we would add our new data to the dictionary:

professors['Harris'] = 'HLTH 101', 'HLTH 102', 'HLTH 110'

Editing a Key-Value Pair

Professor Rasgotra is teaching an additional course. Let’s add this course to the list of courses already associated with her name in our dictionary.

Good news — we already know how to do this. The general format for changing a value in a key-value pair is the same as adding a new key-value pair.

So here is how we update Professor Rasgotra’s key-value pair:

professors['Rasgotra'] = ['SPAN 101', 'SPAN 205', 'SPAN 001']

Now Let’s Learn Some Dictionary Methods

Dictionary methods are tools built into Python that allow us to manipulate dictionaries. Here are a few examples.

1. The get() method

This method returns the value of a key. Here’s the general format:

variable_name = dictionary_name.get(key, alternate_message)

This example includes an alternate message that will be displayed if the key isn’t found. This makes for cleaner-looking output. Including an alternate message is optional, but it’s a great way to handle errors.

2. The pop() method

This method returns a value and removes it (and its associated key) from the dictionary. The general format looks like this:

variable_name = dictionary_name.pop(key)

3. The items() method

This method returns all keys and values of a dictionary. Unlike the previous methods, you don’t need to assign a variable name when writing this statement. Here’s what the format looks like:

variable_name = dictionary_name.items()

Note: this is an extremely abbreviated list of dictionary methods. For a more comprehensive list of methods and how to use them, check out the w3schools tutorial.

Practice with Dictionary Methods

1. Let’s use the get() method to see the courses Professor Rasgotra is teaching this semester.

We’ll use the key “Rasgotra” to find its associated value (her classes).

classes = dictionary.get("Rasgotra")

This statement will give us the following output:

["SPAN 101", "SPAN 205", "SPAN 101"]

2. Professor Smith isn’t teaching this semester after all. Let’s use the pop() method to see and remove Professor Smith and her courses from our dictionary.

We’ll use the key (“Smith”) to return and remove its key-value pair.

smith_info = professors.pop("Smith")

Here’s the output this will produce:

['ENGS 002', 'ENGS 201']

Now, the dictionary ‘professors’ no longer contains the “Smith” key-value pair:

professors = {'Rasgotra' : ['SPAN 101', 'SPAN 205', 'SPAN 001'],
              'Zhang' : ['GEOL 002', 'ENVS 281'],
              'Martinez' : ['MATH 051', 'MATH 052', 'STAT 110'],
              'Harris' : ['HLTH 101', 'HLTH 102', 'HLTH 110']}

3. The admissions department wants a full list of professors and the courses they teach. Let’s use the items() method to do this.

variable_name = dictionary_name.items()

Here’s what the output will look like:

dict_items([('Rasgotra' : ['SPAN 101', 'SPAN 205', 'SPAN 001']),('Zhang', ['GEOG 002', 'ENVS 281']), ('Martinez', ['MATH 051', 'MATH 052', 'STAT 110']), ('Harris', ['HLTH 101', 'HLTH 102', 'HLTH 110'])])

In short: Python dictionaries are fun, often intuitive, and incredibly useful for data management. If you want to learn more about dictionaries, here are some excellent resources to keep learning:

This article was originally published on medium.com. You can read the original article, published in gitconnected’s Level Up Coding, here.

By Ayla Yersel

Humanities nerd learning to code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s