Dictionaries in Python

Dictionaries in Python are versatile data structures that store collections of items as key-value pairs. They offer an efficient way to manage data, allowing rapid access to values using unique keys.

Understanding Python Dictionaries

A dictionary in Python is an unordered collection of items where each item consists of a key-value pair. Keys in a dictionary must be unique and immutable, while values can be of any data type, including lists, tuples, or even other dictionaries.

How to Initialize a Dictionary

Initializing a Python dictionary involves creating a dictionary data structure with initial key-value pairs. There are multiple methods how to add a dictionary in Python.

Using Curly Braces {}

The most common method involves using curly braces {} to define an empty dictionary or a dictionary with predefined key-value pairs. This method allows for quick creation and population of key-value pairs within the dictionary.

Using the dict() Constructor

Python provides a built-in dict() constructor that allows the creation of a dictionary by passing key-value pairs directly or an iterable object containing tuples representing key-value pairs.

Using Dictionary Comprehension

Dictionary comprehension is a concise way to create dictionaries based on specific conditions or iterations. It offers a more dynamic approach to initialize dictionaries by generating key-value pairs from iterables or conditions.

Initializing a dictionary serves as the foundation for storing and organizing data within the key-value structure. These methods provide flexibility in creating dictionaries either with predefined initial data or generating them dynamically based on specific requirements.

Dictionary of Dictionaries

A dictionary of dictionaries, also known as nested dictionaries in Python, is a structure where values within a dictionary are themselves dictionaries. This structure allows for a multi-level hierarchy of data organization. Here is an example of putting a dictionary into a dictionary:

# Creating a dictionary of dictionaries
nested_dict = {
  'person1': {'name': 'Alice', 'age': 30},
  'person2': {'name': 'Bob', 'age': 25}
}
In this structure:
  • The outer dictionary contains keys 'person1' and 'person2'.
  • Each key corresponds to an inner dictionary containing information about a person.
  • The inner dictionaries include keys like 'code' and 'age'.

Accessing values in a dictionary of dictionaries involves chaining keys to access the inner dictionaries' values:

# Accessing data in the nested dictionary
print(nested_dict['person1']['name'])  # Output: Alice
print(nested_dict['person2']['age'])   # Output: 25

Nested dictionaries offer a flexible way to manage structured data. They are particularly useful when dealing with complex data structures, providing a hierarchical approach to store and retrieve information at different levels within a single dictionary. This hierarchical nature enables the organization of diverse and interconnected data elements.

How to Append Elements to Python Dictionary

In Python, dictionaries are dynamic data structures that store information in key-value pairs. While dictionaries do not have an append() method like lists, you can add elements to a dictionary by assigning values to new keys or modifying existing keys.

To add a new key-value pair to a dictionary, you can directly assign a value to a new key:

# Creating an empty dictionary
my_dict = {}

# Adding key-value pairs to the dictionary
my_dict['name'] = 'Alice'
my_dict['age'] = 30
my_dict['city'] = 'Cityville'

This code snippet demonstrates how to add new key-value pairs to the my_dict dictionary. Each line assigns a value to a specific key within the dictionary.

If you wish to modify an existing value, you can directly access the key and reassign its value:

# Modifying an existing value
my_dict['age'] = 31

Here, the age key in the dictionary my_dict is updated to a new value, changing it from 30 to 31.

Adding multiple key-value pairs simultaneously can be achieved using the update() method:

# Adding multiple key-value pairs using update()
my_dict.update({'country': 'Wonderland', 'email': '[email protected]'})

The update() method merges the specified dictionary into the original dictionary. In this case, it adds the keys 'country' and 'email' along with their respective values.

How to Delete an Element From a Dictionary

Using the del Keyword:

The del keyword removes a specific key-value pair from a dictionary.

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Deleting a specific key-value pair
del my_dict['age']

The del statement deletes the key 'age' along with its associated value from the my_dict dictionary.

Using the pop() Method:

The pop() method removes the specified key and returns its corresponding value. It's useful when you need to use or process the deleted value after removing it from the dictionary

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Removing 'age' key and getting its value
deleted_age = my_dict.pop('age')

In this example, the value associated with the key 'age' is removed from my_dict and stored in the variable deleted_age.

Using the popitem() Method:

The popitem() method removes and returns the last inserted key-value pair as a tuple. For Python 3.7 and later versions, dictionaries maintain insertion order.

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Removing the last inserted key-value pair
deleted_item = my_dict.popitem()

The popitem() method removes and returns the key-value pair (key, value) of the last element added to the dictionary my_dict.

Using the clear() Method:

The clear() method removes all elements from the dictionary, effectively making it an empty dictionary.

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Clearing all elements from the dictionary
my_dict.clear()

The clear() method empties the contents of my_dict, leaving it as an empty dictionary.

Iterating Over Dictionary in Python

Iterating over a dictionary in Python allows you to access its keys, values, or both. There are several methods to iterate through a dictionary:

Iterating Over Keys:

You can use a for loop to iterate directly over the keys of a dictionary:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Iterating over values
for value in my_dict.values():
    print(value)  # Accessing each value

The values() method returns a view object containing all the values in the dictionary. You can iterate through this view object to access each value individually.

Iterating Over Both Keys and Values:

To simultaneously iterate over both keys and values, you can use the items() method:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'Cityville'}

# Iterating over key-value pairs
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")  # Accessing key and value simultaneously

The items() method returns a view object containing tuples of key-value pairs. By using this method, you can iterate through the tuples to access both keys and their corresponding values at the same time.

Iterating Over Nested Dictionary:

Consider a nested dictionary as follows:

nested_dict = {
    'person1': {'name': 'Alice', 'age': 30},
    'person2': {'name': 'Bob', 'age': 25}
}

You can iterate through the keys of the outer dictionary (nested_dict) to access the keys of the inner dictionaries:

# Iterating over keys in the outer dictionary
for person_key in nested_dict:
    print(f"Person: {person_key}")

    # Accessing inner dictionary using the outer key
    inner_dict = nested_dict[person_key]

    # Iterating over keys in the inner dictionary
    for key in inner_dict:
        print(f"  {key}: {inner_dict[key]}")

This nested loop first iterates through the keys in the outer dictionary ('person1', 'person2'). For each key, it accesses the corresponding inner dictionary, and then iterates through the keys in the inner dictionary ('name', 'age') to access their respective values.

You can also use items() to directly access both keys and values in the nested dictionary:

# Iterating over key-value pairs in the nested dictionary
for person, details in nested_dict.items():
    print(f"Person: {person}")

    # Iterating over key-value pairs in the inner dictionary
    for key, value in details.items():
        print(f"  {key}: {value}")

This method allows you to iterate through the key-value pairs in both the outer and inner dictionaries simultaneously, providing a cleaner approach to access keys and values in nested structures.

How to Convert a List & String to a Dictionary

Converting a list or a string to a dictionary in Python involves using specific methods tailored to the data structure and content.

Converting a List to a Dictionary:

If you have a list of tuples where each tuple represents key-value pairs, you can convert it to a dictionary using dictionary comprehension or the dict() constructor.

Using dictionary comprehension:

list_of_tuples = [('a', 1), ('b', 2), ('c', 3)]

# Using dictionary comprehension
dict_from_list = {key: value for key, value in list_of_tuples}

Using dict() constructor:

list_of_tuples = [('a', 1), ('b', 2), ('c', 3)]

# Using dict() constructor with list of tuples
dict_from_list_alt = dict(list_of_tuples)

These methods allow you to convert a list of tuples representing key-value pairs into a dictionary in Python.

Converting a String to a Dictionary

Converting a string to a dictionary depends on the format of the string data.

Using json.loads() (for JSON-like strings).

If your string data resembles a JSON format (key-value pairs in double quotes), you can use the json.loads() method from the json module to convert it into a dictionary.

Example:

import json

string_data = '{"name": "Alice", "age": 30, "city": "Cityville"}'

# Converting string to dictionary using json.loads()
dict_from_string = json.loads(string_data)

Converting a string with key-value pairs to a dictionary.

If your string contains key-value pairs separated by a specific delimiter, you can split the string and convert it into a dictionary by manipulating the resulting list.

Using split() and strip():

string_with_pairs = 'name:Alice|age:30|city:Cityville'

# Splitting the string and converting to dictionary
dict_from_string_with_pairs = dict(item.split(':') for item in string_with_pairs.split('|'))

These methods offer ways to convert a string or a list of tuples into a dictionary, providing flexibility based on the data format and content.

Profile picture for user Sarah Chen

The only author and editor of all pages on the site. Most of what I write about is based on years of book reading on the topic.

Updated: 15 March 2024