Dictionaries in Python: What They Are and How to Use Them

In this guide, you'll learn what are Dictionaries in python and how to use them to your advantage in your Python Projects.

Dictionaries are one of the most important, and widely used, data structures in Python. You can use them to store lists of strings, numbers, or even other dictionaries! In this guide, you’ll learn what they are and how to use them to your advantage in your Python projects.


Introduction: Defining a Dictionary

Dictionaries are one of Python’s handiest built-in data structures. In essence, they allow you to define your own key-value pairs using simple Python syntax. Unlike lists, dictionaries can contain values that are not numbers or strings; they may be any type of object such as a list, dictionary, string, integer, or boolean value. This makes them very powerful and flexible. Let's see how we can define the syntax of dictionaries in python,

dict = {
    <key1>:<value1>,
    <key2>:<value2>,
    <key3>:<value3>,
    .
    .
    .
   
}

A dictionary mainly contains a key-value pair. The key is used to access its value. Each key is unique and cannot be repeated within a single dictionary. We can create dictionaries using curly braces {}. The values inside these curly braces are enclosed by either double or single quotes. If we want to add more than one value, then separate them with commas(,) as shown above: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}. If you have just one value, you don't need any quotes around it. For example, {'key1': 1} is also valid syntax for creating a dictionary in python.

Well, if the syntax doesn't look clear to you, let's see how a dictionary is actually implemented in python,

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
}

Here we've created a dictionary called 'book' that contains the title and author as keys with its corresponding values.

Accessing Dictionary Values

In Python, a dictionary is an unordered collection of values, which are referenced using a key. The value associated with a key can be of any object type. If you want to retrieve a value based on its key, use square brackets: my_dict['key'], where my_dict is a dictionary instance.

Suppose you want to access the title and author name from the 'book' dictionary we have created, you can simply specify those keys inside the square brackets with the name of the dictionary just like this:

>>> book['title']
Rich Dad Poor Dad
>>> book['Author']
Robert Kiyosaki

Now let's combine the results in one line,

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
}

title = book['title']
author = book['Author']

print("The book " + title + " is written by " + author)

The book Rich Dad Poor Dad is written by Robert Kiyosaki

Just simple stuff, but what if you specified a key that is not present in the dictionary:

>>> book['year']
Traceback (most recent call last): File "E:\Python Projects\twitterbot\test.py", line 6, in <module> date_published = book["date"] # Accessing the title of the book KeyError: 'year'

Python raises an exception when you try to access a key that doesn't exist in the dictionary.

Adding Key-Value pairs to a Dictionary

Now let's see how we can insert an element into a dictionary, So you are willing to add two more key-value pairs to our 'book' dictionary which are the year and month the book has been published. For doing that you need to create a new key and value pairs like this:

book['year'] = 1997
book['month'] = "April"
print(book)


{'title': 'Rich Dad Poor Dad', 'Author': 'Robert Kiyosaki', 'year': 1997, 'month': 'April'}

The new key-value pair will be added to the dictionary when running this code. Remember that dictionaries are unordered collections of data. That means that when you're adding new entries to your dictionary, you don't have to worry about inserting them into any particular order. In fact, you can't really insert them into any particular order!

Removing Key-Value pairs from a Dictionary

To delete an element from a dictionary, you can use a keyword known as del. The syntax for deleting an entry is del dictionary_name['key']. Here's how it works:

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
    "year": 1997,
    "month":"April"
}

del book['year']

print(book)

{'title': 'Rich Dad Poor Dad', 'Author': 'Robert Kiyosaki', 'month': 'April'}

As you can see that the key 'year' from the dictionary 'book' is being deleted. You don't need to specify the value in order to delete a particular key-value pair, the value and key together will be removed from the dictionary by only specifying the key. It’s important to note that you cannot delete a specific element from a dictionary using its position like we do in lists. It will throw a KeyError.

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
    "year": 1997,
    "month":"April"
}

del book[1]

Traceback (most recent call last): File "E:\Python Projects\twitterbot\test.py", line 8, in <module> del book[1] KeyError: 1

Modifying values in a Dictionary

Modification is also important as same as insertion and deletion, it helps us change and alter the dictionary throughout the program. There are two ways you can modify an existing value in a dictionary. The first one is to directly assign the value to the existing key,

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
    "year": 1997,
    "month":"April"
}

book['title'] = "Harry Potter Philosopher's Stone"
book['Author'] = "JK. Rowling"
book['month'] = "June"


print(book)

{'title': "Harry Potter Philosopher's Stone", 'Author': 'JK. Rowling', 'year': 1997, 'month': 'June'}
  
Another way of modifying a dictionary is by the python built-in update() method.

book = {
    "title":"Rich Dad Poor Dad",
    "Author":"Robert Kiyosaki",
    "year": 1997,
    "month":"April"
}

book.update(

    {
   
    "title":"Harry Potter Philosopher's Stone",
    "Author":"JK. Rowling",
    "month":"June"
   
    }
)


print(book)

{'title': "Harry Potter Philosopher's Stone", 'Author': 'JK. Rowling', 'year': 1997, 'month': 'June'}

Iterating Through a Dictionary

You can also loop through a dictionary by using the fancy for loop, which is much easier than writing out all of your keys. This will allow you to access each key-value pair as you iterate through it. One condition is that, when iterating through a dictionary, you’ll have to use two indices—one for accessing keys and one for accessing values. Here’s an example:

book = {
    "title":"Harry Potter Philosopher's Stone",
    "Author":"J.K. Rowling",
    "year": 1997,
    "month":"June"
}

for key, value in book.items():
    print("Key:",key, "\tvalue:", value)

Key: title value: Harry Potter Philosopher's Stone Key: Author value: J.K. Rowling Key: year value: 1997 Key: month value: June

Here, there are two things to note, first is that we require two variables to access the key and value of the dictionary in the for loop, second is the item() method which is essential to retrieve a list of key-value pairs.

But can we access the key and value individually in a dictionary? yes, it's possible. You can individually loop through a key and value by using the keys() and values() method. Let's see how:

for key in book.keys():
    print(key)

print("\n")

for value in book.values():
    print(value)

title Author year month Harry Potter Philosopher's Stone J.K. Rowling 1997 June

Nested Dictionaries

A dictionary inside another dictionary is known as a nested dictionary. The nested dictionaries are used for a variety of purposes such as storing data or performing complex calculations. Nested dictionaries are used to store hierarchical data. The hierarchy is created using parenthesis and commas (,) with each level separated by a comma. For example, if you want to create a dictionary for grades of students you can simply use a nested dictionary.

grades = {
   
    "James":{"Maths":90,"Science":97},
    "Sara":{"Maths":87,"Science":99}
   
    }

Accessing elements from the nested dictionary

We learned how to access elements from a dictionary,  but what if you want to access an element from a nested dictionary? To do that, we use indexing.  The syntax is similar to accessing a nested list item by its position.

james_grade_in_maths = grades['James']['Maths']
saras_grade_in_science = grades['Sara']["Science"]

print("James grade in maths:", james_grade_in_maths)
print("Sara's grade in science:", saras_grade_in_science)

James grade in maths: 90 Sara's grade in science: 99

Inserting elements to the nested dictionary

So let's say we need to add one more key-value pair in 'grades' which is the average of grades scored by James and Sara in Maths and Science. Here is how it can be done:

grades['James']["Average"] = (90 + 97)/2
grades['Sara']['Average'] = (87 + 99)/2

print("James average score:",grades['James']['Average'])
print("Sara's average score:",grades['Sara']['Average'])

James average score: 93.5 Sara's average score: 93.0

Iterating Through a Nested Dictionary

In order to iterate through a nested dictionary, we need to use two loops, one for each level of depth. The outer loop will be used to iterate over each key-value pair within that level of depth. The inner loop will be used to iterate over each value associated with that key.

for names, subs in grades.items():
    print("\n",names)
    for sub, grade in grades[names].items():
        print(sub, grade)

James Maths 90 Science 97 Sara Maths 87 Science 99

List inside a Dictionary

It is possible to include lists as values inside a dictionary, and it can be useful. If you have a list of keys that you want to use multiple times, you can put them into a dictionary. For instance, if you want to find the total average of a list of grades scored by two students, you can do it like this:

grades = {

    "James":[77, 90, 97, 68, 87],
    "Sara":[67, 99, 87, 70, 89]
   
    }

sum = 0

for key, grade_lists in grades.items(): # looping through the dictionary
    for i in grade_lists: # Looping through the list
        sum+=i # Finding the sum of all the elements in the list

avg = sum/10 # finding the average
print("The average of marks scored by James and Sara is:", avg)

The average of marks scored by James and Sara is: 83.1

The dict() method

Python dictionary comes with a built-in dictionary constructer, dict(). This method takes key/value pairs as arguments. It returns a new dictionary object whose keys are taken from its parameter list. For example, dict(one=1, two=2) returns {'one': 1, 'two': 2}. Keys can be any hashable object. Values can be any immutable object (numbers, strings, etc.). The values are not required to be hashable objects. So dict(one=1) returns {'one': 1}. In fact dict() is just an alias for {}.

my_dict = dict(name="Sidharth", age=20)

print(my_dict)

{'name': 'Sidharth', 'age': 20}

The dict() constructer is useful when you have a list of key/value pairs, but you want to convert it into a dictionary. You can also use it as an alternative way of creating dictionaries when there are no good arguments for using {}.