What is a Python Dictionary?

A Python dictionary is a data structure that allows you to store and retrieve data using key-value pairs. Think of it as a real-life dictionary where you can look up a word (key) and find its corresponding definition (value). Python dictionary provide a convenient way to organize and manipulate data, making them an essential component of your programming arsenal.

What are the keys and values of a dictionary?

The keys in a Python dictionary can be of any immutable data type, such as strings, numbers, or tuples. On the other hand, the values can be of any data type, including lists, dictionaries, or even custom objects. This flexibility makes dictionaries incredibly versatile for storing and organizing data.

To put it simply, the keys are like the index in a book, helping you locate the information you need, while the values are the valuable pieces of information associated with each key. By understanding the relationship between keys and values, you can harness the full potential of dictionaries in your Python programs.

Let’s embark on an exciting journey of Python dictionary! In this tutorial, you’ll learn everything you need to know about dictionaries, from creating them to removing elements, all with easy-to-understand examples. By the end, you’ll have a solid grasp of dictionaries in Python and how to wield their power in your Python code.

Python Dictionary Syntax and Parameters

Before we delve into the practical aspects, let’s take a moment to understand the syntax and parameters of Python dictionary. In its simplest form, a dictionary is defined using curly braces {}. Each key-value pair is separated by a colon :. Let’s take a look at an example:

my_dict = {"name": "John", "age": 25, "city": "New York"}

Above, we have a dictionary my_dict with three key-value pairs. The keys are "name", "age", and "city", while the corresponding values are "John", 25, and "New York".

Python dictionary Examples

There are several ways you can create Python dictionary and populate it with keys and values. Let’s explore most used methods:

I. Creating a Dictionary and Setting Initial Values

To create a dictionary, you can assign key-value pairs directly or use the built-in dict() constructor. Let’s see both approaches in action:

Direct assignment:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} print(my_dict)

dict() constructor:

Example Code
my_dict = dict(name="John", age=25, city="New York") print(my_dict)

In both cases, we have created a Python dictionary with the same key-value pairs. You will see same output while execution of above examples:

{‘name’: ‘John’, ‘age’: 25, ‘city’: ‘New York’}

Feel free to choose the approach that suits your coding style and preferences.

II. Accessing Dictionary Elements

Now that we have a dictionary, it’s time to learn how to access its elements. You can retrieve the value associated with a specific key by using the square brackets [] notation. Let’s see an example:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} print(my_dict["name"])

Here, we access the value associated with the key "name" and print it to the console. The output will be:


III. Adding Elements in Dictionary

To add new elements to a dictionary, you can simply assign a value to a new key or an existing key. Let’s see an example:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} my_dict["occupation"] = "Engineer" print(my_dict)

In this example, we add a new key-value pair "occupation": "Engineer" to the dictionary. The output will be:

{‘name’: ‘John’, ‘age’: 25, ‘city’: ‘New York’, ‘occupation’: ‘Engineer’}

IV. Modifying Dictionary Elements

To modify the value of an existing key in a dictionary, you can simply assign a new value to that key. Let’s see an example:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} my_dict["age"] = 26 print(my_dict)

In this example, we modify the value associated with the key "age" from 25 to 26. The output will be:

{‘name’: ‘John’, ‘age’: 26, ‘city’: ‘New York’}

V. Copying Dictionary Elements

To create a copy of a dictionary, you can use the copy() method or the dictionary constructor dict(). Let’s see an example:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} new_dict = my_dict.copy() print(new_dict)

In this example, we create a new dictionary new_dict that is a copy of my_dict. The output will be the same as my_dict:

{‘name’: ‘John’, ‘age’: 25, ‘city’: ‘New York’}

VI. Removing Dictionary Elements

To remove an element from a dictionary, you can use the del keyword followed by the key you want to remove. Let’s see an example:

Example Code
my_dict = {"name": "John", "age": 25, "city": "New York"} del my_dict["age"] print(my_dict)

Here, we remove the key-value pair associated with the key "age" from the dictionary. The output will be:

{‘name’: ‘John’, ‘city’: ‘New York’}

VII. Merging Multiple Dictionaries

To merge dictionaries, you can use the update() method, which takes another dictionary as an argument and adds its key-value pairs to the original dictionary. Let’s look at an example to understand how it works:

Example Code
dict1 = {'name': 'John', 'age': 25} dict2 = {'country': 'USA', 'occupation': 'Engineer'} dict1.update(dict2) print("Merged dictionary:", dict1)

In this example, we have two dictionaries, dict1 and dict2, containing different key-value pairs. By calling the update() method on dict1 and passing dict2 as an argument, we merge the two dictionaries. The update() method modifies dict1 by adding the key-value pairs from dict2 to it.

When we run this code, the output will be:

Merged dictionary: {‘name’: ‘John’, ‘age’: 25, ‘country’: ‘USA’, ‘occupation’: ‘Engineer’}

As you can see, the dictionaries are merged, and the resulting dictionary contains all the key-value pairs from both dict1 and dict2.

It’s important to note that if there are common keys between the dictionaries being merged, the values from the second dictionary (in this case, dict2) will overwrite the values of the first dictionary (in this case, dict1). This behavior allows you to update or replace specific key-value pairs during the merging process.

Now that you have a basic understanding of Python dictionaries, let’s delve into some advanced examples to further enhance your knowledge. We’ll explore more complex scenarios where dictionaries can be incredibly useful. By going through these examples, you’ll gain a deeper understanding of Python dictionaries. So, let’s dive in and expand your knowledge!

VIII. Nested Dictionaries: Creating Complex Data Structures

Python dictionary can contain nested dictionaries as their values, allowing you to create complex data structures. This feature is incredibly useful when you need to organize and store hierarchical or nested data. Let’s explore how to create dictionaries with nested dictionaries.

To create a Python dictionary with nested dictionaries, you can simply assign a dictionary as the value for a specific key in another dictionary. This nested dictionary can contain its own key-value pairs, forming a hierarchical structure. Here’s an example:

Example Code
student1 = {'name': 'John', 'age': 20} student2 = {'name': 'Jane', 'age': 22} course = {'course_name': 'Math', 'students': {}} course['students']['student1'] = student1 course['students']['student2'] = student2 print(course)

In this example, we have two student dictionaries, student1 and student2, representing information about different students. We also have a course dictionary, which contains a key-value pair for the course name and an empty dictionary for the students key.

By assigning the student1 and student2 dictionaries as the values for the course['students']['student1'] and course['students']['student2'] keys, respectively, we create a nested structure. The output will be:

{‘course_name’: ‘Math’, ‘students’: {‘student1’: {‘name’: ‘John’, ‘age’: 20}, ‘student2’: {‘name’: ‘Jane’, ‘age’: 22}}}

As you can see, the students key in the course dictionary now contains a nested dictionary with the student information.

Using nested dictionaries allows you to organize and represent complex data relationships in a structured and intuitive way. You can access the nested dictionary values using multiple keys, such as course['students']['student1']['name'], which would give you the name of the first student.

IX. Storing and Manipulating Custom Objects

Python dictionaries can also store custom objects as their values. This capability provides a convenient way to associate specific data or attributes with individual objects. Let’s see how we can store and manipulate custom objects in a dictionary.

To store custom objects in a dictionary, you can use the object instances as the values for specific keys. Each object instance can have its own attributes and methods, allowing you to access and manipulate the data associated with that object. Here’s an example:

Example Code
class Person: def __init__(self, name, age): self.name = name self.age = age person1 = Person('John', 25) person2 = Person('Jane', 30) people = {'person1': person1, 'person2': person2} print(people['person1'].name) print(people['person2'].age)

In this example, we define a Person class with name and age attributes. We then create two Person instances, person1 and person2, with different attribute values.

By assigning these instances as the values for the people['person1'] and people['person2'] keys, we store the custom objects in the people dictionary. We can access and manipulate the object attributes as demonstrated in the print statements. The output will be:


As you can see, we accessed the name attribute of person1 and the age attribute of person2 directly from the dictionary.

Storing custom objects in dictionaries can be advantageous when you want to associate specific data or attributes with individual instances. It allows for easy retrieval and manipulation of the object data within the context of a larger data structure.

X. Python Dictionary as a Lookup Table

Python dictionaries are often used as lookup tables, providing an efficient way to retrieve data based on a given key. This usage pattern leverages the dictionary’s underlying hash table implementation, allowing for fast and constant-time access to values. Let’s explore how dictionaries can serve as efficient lookup tables.

To use a dictionary as a lookup table, you store values associated with unique keys. When you need to retrieve a value, you provide the corresponding key, and Python quickly calculates the hash of the key to locate the value in the dictionary’s internal data structure. This process ensures fast and efficient retrieval, even with large dictionaries. Here’s an example:

Example Code
population = {'USA': 328_200_000, 'China': 1_409_517_397, 'India': 1_366_417_754} country = 'China' if country in population: print(f"The population of {country} is {population[country]}") else: print(f"Population data for {country} is not available.")

In this example, we have a population dictionary that stores the populations of different countries. We want to retrieve the population of a specific country, so we provide the country variable as the key to access the corresponding value.

By using an if statement to check if the country key exists in the population dictionary, we ensure that we only access the value if it’s available. If the key exists, we print the population of the country; otherwise, we display a message indicating that the data is not available. The output will be:

The population of China is 1409517397

XI. Dictionary Comprehensions

In addition to list comprehensions, Python also supports dictionary comprehensions, which allow you to create dictionaries in a concise and expressive manner. Dictionary comprehensions provide a compact syntax for generating dictionaries from iterable sources or transforming existing dictionaries. Let’s explore how to use dictionary comprehensions.

To create a dictionary using a comprehension, you can specify the key-value pairs in a compact form using a loop and conditionals (if desired). The resulting dictionary is constructed by iterating over an iterable source and applying the defined logic for each item. Here’s an example:

Example Code
numbers = [1, 2, 3, 4, 5] squared_numbers = {num: num**2 for num in numbers} print(squared_numbers)

In this example, we have a list of numbers, numbers, and we want to create a dictionary where each number is a key, and its square is the corresponding value. By using a dictionary comprehension, we iterate over the numbers list, assign each number as a key, and calculate its square as the value.

The resulting squared_numbers dictionary will be:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

As you can see, the dictionary comprehension generates the key-value pairs according to the specified logic, resulting in a dictionary where each number is mapped to its square.

Dictionary comprehensions can also be used to transform existing dictionaries. You can iterate over the key-value pairs of an existing dictionary and apply certain operations to create a new dictionary. Here’s an example:

Example Code
person = {'name': 'John', 'age': 30, 'country': 'USA'} person_initials = {key: value[0] for key, value in person.items() if key != 'country'} print(person_initials)

In this example, we have a person dictionary containing information about a person’s name, age, and country. We want to create a new dictionary, person_initials, where the keys represent the original keys of person (except ‘country’), and the values are the first initials of each corresponding value.

The resulting person_initials dictionary will be:

{‘name’: ‘J’, ‘age’: 3}

As you can see, the dictionary comprehension iterates over the key-value pairs of person, excluding the ‘country‘ key, and creates a new dictionary with the desired transformation.

Congratulations on reaching the end of this tutorial on Python dictionary! You’ve gained a solid understanding of what dictionaries are, how to create them, and how to perform various operations on them.

Throughout this Python Helper tutorial, you’ve gained proficiency in a multitude of techniques for effectively working with dictionaries. These techniques include creating dictionaries with initial values, accessing elements using keys, adding and modifying elements, copying dictionaries, merging multiple dictionaries, and even constructing complex data structures with nested dictionaries. Additionally, you’ve explored how dictionaries can be employed to store and manipulate custom objects, as well as to serve as highly efficient lookup tables.

Keep practicing and exploring the vast possibilities of Python dictionaries. The more you work with them, the more you’ll realize their immense value in solving real-world problems. Happy coding!

Scroll to Top