Python Dictionary Tutorial

dictionaries in python

Dictionaries in Python allow programmers to associate pieces of related information. Each piece of information in a dictionary is stored as a key-value pair. These are similar to associative arrays in other popular programming languages. To access the value in a dictionary, you provide the associated key. You can loop over dictionaries while accessing all of the values, keys, or the entire key-value pair. In this tutorial, we’ll take a look at how to create a dictionary, how to get the value of a key, how to put a dictionary in a list, how to add new key-value pairs, how to modify values, and more.


How To Create A Dictionary

To create a dictionary in Python, you can make use of the curly braces { }. Inside of the curly braces, a colon : is used to associate various key-value pairs.

Making a dictionary

python make a dictionary


Getting The Value Of A Key

There are a couple of ways to use the values stored in dictionaries. To access the value associated with a specific key, you can specify the name of the dictionary and then place the key inside a set of square brackets [ ]. If you try to access a key that does not exist, Python will output a KeyError message. There is also a get() method, which returns None instead of an error if the key doesn’t exist. It is also possible to specify a default value to use if the key is not in the dictionary.

Accessing the value associated with a given key

pycharm dictionary output

Using the get() method to access a value

python dictionary get method


Dictionaries Inside Lists

It is possible to define a dictionary and then store it inside of a list. This is what is known as Nesting.

Storing dictionaries within a list

last: Diaz
first: Guillermo
profilename: gDiaz
last: Rezende
first: Pedro
profilename: pRezende

dictionary nest inside list

Defining a list of dictionaries without using append()

last: Diaz
first: Guillermo
profilename: eDiaz
last: Rezende
first: Pedro
profilename: mRezende

python data in dictionary


Adding New Key-Value Pairs

The only limit to how many key-value pairs you can store in a dictionary is determined by the amount of memory on the machine the Python program is running on. Of course, you’ll likely never need that many key-value pairs, but it’s good to know you could have millions of them if you so desired. You can add a new key-value pair to an existing dictionary by giving the name of the dictionary and the new key in square brackets. Then, set the new value into that expression. You can start with an empty dictionary and add key-value pairs as needed.

Adding a key-value pair

The above code may also be written as a dictionary literal like so.

Adding to an empty dictionary


How To Modify Values

Since a dictionary is mutable, you can change the value associated with any key in the dictionary. Provide the name of the dictionary and
enclose the key in square brackets, then provide the new value for that key to modify the original value.

Modifying values in a dictionary

{'level': 'novice', 'points': 7}
{'level': 'intermediate', 'points': 10}

modify python dictionary


Removing key-value pairs

To remove a key-value pair from a dictionary, you can use the del keyword. Use the del keyword, then provide the dictionary name, followed by the key in square brackets. This will remove the key and its associated value from the dictionary.

Deleting a key-value pair

{'level': 'novice', 'points': 7}
{'level': 'novice'}

Storing a list inside a dictionary allows you to associate more than one value with each key.
Storing lists in a dictionary

Pedro: 
- Outer Wilds
- Disco Elysium
Sean: 
- Baba Is You
Daniel: 
- Sekiro
- Star Wars Jedi
Guillermo: 
- Control
- Dragon Quest Builders 2

python nested lists dictionaries


Dictionary of dictionaries

You can store a dictionary inside another dictionary. In this case, each value associated with a key is itself a dictionary.

Storing dictionaries in a dictionary

Username: smcloughlin
	Full name: Sean Mcloughlin
	gender: Male

Username: prezende
	Full name: Pedro Rezende
	gender: Male

python dictionaries in a dictionary

Avoid Excessive Nesting

Nesting can be very useful in some situations. The downside is that this can make the code more complex than what is ideal. If you find yourself nesting items deeper than the examples here, then there are probably better ways of managing your data. One option is to use Classes to handle data management.


Looping through a dictionary

There are three different ways to loop over a dictionary. The first is to loop through all of the values in the dictionary. The next is to loop over all of the keys. The last is to loop over all of the key-value pairs together. Different problems require different approaches. As you add key-value pairs to a dictionary, it will keep track of the order in which they were added. To process the data in a different order, you can sort the keys in the loop.

Looping through all key-value pairs

store key value pairs in dictionary

George: Crash Bandicoot
Alex: Super Smash Bros
Sarah: Legend Of Zelda
Allison: Pong

Looping through all the keys

George
Alex
Sarah
Allison

Looping through all the values

Looping through all the keys in reverse order

Sarah: Legend Of Zelda
George: Crash Bandicoot
Allison: Pong
Alex: Super Smash Bros

Checking The Length Of A Dictionary

You can find the number of key-value pairs in a dictionary by using the len() function.

Determine a dictionary’s length

4

Dictionary Comprehensions

Just like a list has the feature of comprehension, so too do dictionaries. A comprehension is just a compact way of creating a dictionary. To make a dictionary comprehension, define an expression for the key-value pairs you want to make. Then write a for loop to generate the values that will feed into this expression. The zip() function matches each item in one list to each item in a second list. It can be used to make a dictionary from two lists.

Using a loop to create a dictionary

Using a loop to create a dictionary

Using a dictionary comprehension

Using a dictionary comprehension

Using zip() to make a dictionary

Using zip to make a dictionary

Creating thousands of dictionaries

To create a large number of dictionaries at once, you can use a loop like so.

Number of players created:
1000

Learn More About Dictionaries In Python


Dictionaries In Python Summary

Python’s dictionary type is a hashed key-value structure. This is comparable to associative arrays in other languages like PHP and JavaScript. A dictionary is created using curly braces with an opening curly brace and a closing curly brace. Inside of the curly braces is the key-value pairs. Each of the key-value pairs has a key on the left, a value on the right and they’re separated by a colon. The pairs themselves are separated by commas within the structure sets. You can also create the dictionary using the dictionary constructor and keyword arguments. Keys and values may be any type. Keys must be immutable. Strings and numbers can always be keys. The items() method returns a view of key-value pairs. The keys() method returns a view of dictionary keys and the values() method gives us just a list of the values. A dictionary is indexed by its keys so you can easily pick a particular element. If you try to access a key that doesn’t exist you’ll get a key error exception. On the other hand, you can use the get() method to return a value when you don’t know if the key exists. Python’s dictionary type is both simple and useful, and you’ll see many examples of it in code for common Python projects.