Learn Python

Dictionaries in Python

What is a Dictionary in Python?

A dictionary in Python is an unordered collection of data objects, where each element is stored as key-value pairs. It allows for efficient retrieval of values using their associated keys. In other programming languages, dictionaries are also referred to as associative arrays or hash maps. In Python, dictionaries are defined using curly brackets {}, with each key-value pair separated by a colon. The keys in a dictionary are unique and immutable, whereas the values can be mutable or immutable. Dictionaries are commonly used in scenarios where fast and efficient data access is required, such as looking up values based on specific criteria or organizing data in a structured manner.

Why are Dictionaries Important in Python Programming?

Dictionaries play a crucial role in Python programming, offering a powerful way to organize and manipulate data. One key reason is their ability to associate a value with a unique key and quickly access this value. Unlike lists, which rely on indices to access elements, dictionaries use keys, allowing for efficient and direct retrieval of values.

Dictionaries operate faster than lists, primarily due to their hashable keys. In Python, keys are hashed using the hash() function, resulting in a unique numeric representation for each key. This hashing process enables direct access to values without needing to iterate through the entire dictionary. Consequently, dictionaries provide an efficient solution when working with large datasets or performing frequent lookups.

Another key advantage of dictionaries is the ease with which they facilitate finding values. Instead of relying on memory-consuming iterations, dictionaries store data in key-value pairs. This structure allows programmers to quickly identify the associated value by referencing its key. As a result, searching for specific values becomes significantly streamlined and more straightforward.

Creating and Accessing Dictionaries

Creating and accessing dictionaries is a fundamental concept in programming. Dictionaries store key-value pairs, allowing you to associate values with specific keys. In this guide, you will learn how to create dictionaries using different methods, such as using curly braces or the dict() function. Additionally, you will understand how to access and retrieve values from dictionaries by using their keys.

Creating a Dictionary

To create a dictionary in Python, you can use either curly braces or the dict() method. The curly braces method is more commonly used and is considered more concise. You simply enclose key-value pairs in curly braces, with each pair separated by a comma. For example: {key1: value1, key2: value2}.

If you prefer a more explicit approach, you can use the dict() method. Inside the parentheses, you pass in key-value pairs as arguments using the = sign. For example: dict(key1=value1, key2=value2).

When creating a dictionary, it is important to note that dictionary keys must be immutable. This means they cannot be changed after they are created. Immutable data types, such as tuples, strings, and integers, can be used as dictionary keys. On the other hand, mutable objects like lists cannot be used as keys.

It is also crucial to have unique keys in a dictionary. If you try to assign a new value to an existing key, it will overwrite the previous value. However, if you try to assign a value to a new key, it will be added as a new key-value pair.

To modify the value of a specific key in a dictionary, you can directly access it using the key name and assign a new value to it. For example: my_dict[key] = new_value. This will update the value associated with that key.

Accessing Elements in a Dictionary

Accessing elements in a dictionary involves using the key name inside square brackets to retrieve the desired value. Here are the steps to access elements in a dictionary:

  1. Identify the dictionary you want to access.
  2. Use the key name inside square brackets immediately after the dictionary name. For example, if we have a dictionary called my_dict and we intend to access the value associated with the key name, we would write my_dict['name'].
  3. If the dictionary has nested dictionaries, use the indexing [] syntax to access elements further inside the nested structure. For example, my_dict['person']['age'].
  4. The output of accessing elements in a dictionary is the value associated with the specified key.

Modifying Elements in a Dictionary

To modify elements in a dictionary, you can utilize the update() method. This method allows us to update an existing key's value or add nested key values to the dictionary.

To use the update() method, simply call it on the dictionary object and pass in another dictionary or an iterable of key-value pairs. The existing keys in the dictionary will be updated with the new values, and any new keys will be added along with their respective values.

If the key-value pair already exists in the dictionary, the value will be updated. However, if the key does not exist, a new key with the given value will be added. This makes the update() method a flexible way to modify elements in a dictionary without having to worry about whether the key already exists or not.

Dictionary Operations

Dictionary operations refer to various tasks that can be performed on dictionaries, such as accessing values, adding or removing key-value pairs, modifying existing values, and checking for the existence of keys.

Adding Elements to a Dictionary

To add elements to a dictionary, you need to specify the key and its corresponding value.

To add a single value to a dictionary, you can assign a value to a new key. For example:

my_dict = {}
my_dict["key"] = "value"

To update an existing value in a dictionary, you can assign a new value to an existing key. If the key already exists, the value gets updated. If the key does not exist, a new key with the value is added.

In addition to single values, you can also add nested key-value pairs to a dictionary. For example:

my_dict["key1"] = {"key2": "value2"}

Removing Elements from a Dictionary

Removing elements from a dictionary can be accomplished using the del statement, the pop() method, or the clear() method.

The del statement can be used to remove a specific key-value pair from a dictionary. For example:

my_dict = {"apple": 3, "banana": 5, "orange": 2}
del my_dict["banana"]

The pop() method removes a key-value pair from the dictionary and returns its corresponding value. For example:

my_dict = {"apple": 3, "banana": 5, "orange": 2}
my_dict.pop("banana")

The clear() method removes all key-value pairs from a dictionary, making it empty. For example:

my_dict = {"apple": 3, "banana": 5, "orange": 2}
my_dict.clear()

Updating Elements in a Dictionary

To update elements in a dictionary, you can utilize various methods such as adding, modifying, or deleting entries.

To add new key-value pairs to a dictionary, you can use the syntax Dict[Key] = 'Value'. This allows you to create a new entry or update an existing one.

Similarly, you can update existing values in a dictionary using the update() method. This method takes another dictionary as an argument and merges its key-value pairs with the original dictionary. If a key from the new dictionary already exists in the original one, the corresponding value will be updated.

If you want to delete a specific entry from a dictionary, you can use the del statement. By specifying the key to be deleted, you can remove the corresponding key-value pair from the dictionary.

Dictionary Methods

Dictionary methods provide various functions that enable the manipulation and retrieval of data from dictionaries. By exploring these methods, programmers gain powerful tools to manage and organize data efficiently.

Common Methods Used with Dictionaries

  1. update(): Add or update key-value pairs in a dictionary by providing another dictionary or an iterable of key-value pairs.
  2. pop(): Remove a key-value pair from the dictionary and return its corresponding value. You can specify a default value to be returned if the key does not exist.
  3. del: Remove a specific key-value pair from a dictionary by using the del statement and specifying the key to be deleted.
  4. clear(): Remove all the key-value pairs from a dictionary, effectively emptying it.
  5. keys(): Return a list of all the keys in the dictionary.
  6. values(): Return a list of all the values in the dictionary.
  7. items(): Return a list of key-value pairs.
Written by

Master Python by choosing your ideal learning course

View all courses

Create a free account to access the full topic

Sign up with Google
Sign up with Google
Sign up with JetBrains
Sign up with JetBrains
Sign up with Github
Sign up with GitHub
Coding thrill starts at Hyperskill
I've been using Hyperskill for five days now, and I absolutely love it compared to other platforms. The hands-on approach, where you learn by doing and solving problems, really accelerates the learning process.
Aryan Patil
Reviewed us on