Home » Python Dictionaries : A Tutorial

Python Dictionaries : A Tutorial

Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
Spring Framework Basics Video Course

In Python, a dictionary is an unordered collection of items that are stored as key-value pairs. Each key is unique, and it maps to a value. Dictionaries are mutable, meaning that you can change, add, or remove key-value pairs after they are created.

Dictionaries are useful for storing data that is logically paired, such as names and phone numbers, or country names and capitals.

This tutorial will cover how to create dictionaries, access and modify elements, and perform various operations with practical examples.

1. Creating a Dictionary

You can create a dictionary by placing a comma-separated list of key-value pairs inside curly braces {}, or by using the built-in dict() function.

Example: Creating a Dictionary

# Example: Creating a simple dictionary
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

In this example:

The dictionary person contains three key-value pairs, where “name”, “age”, and “city” are keys and “Alice”, 25, and “New York” are their corresponding values.

Example: Creating a Dictionary Using dict()

# Example: Creating a dictionary using dict()
person = dict(name="Alice", age=25, city="New York")
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

In this example:

The dict() function is used to create the same dictionary as above.

2. Accessing Dictionary Elements

You can access values in a dictionary by using the key inside square brackets [] or the get() method.

Example: Accessing Values by Key

# Example: Accessing values in a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing a value using a key
print(person["name"])  # Output: Alice
print(person["age"])   # Output: 25

In this example:

person[“name”] accesses the value associated with the key “name”.

Example: Using the get() Method

The get() method returns the value for the specified key if it exists, and None or a default value if the key is not found.

# Example: Using get() to access values
print(person.get("city"))  # Output: New York
print(person.get("country"))  # Output: None (key not found)

# Providing a default value
print(person.get("country", "USA"))  # Output: USA (default value)

In this example:

get(“city”) returns the value for “city”, and get(“country”) returns None because “country” does not exist in the dictionary.

3. Modifying Dictionary Elements

You can modify the value of an existing key or add new key-value pairs by using square brackets.

Example: Modifying and Adding Elements

# Example: Modifying and adding elements
person = {"name": "Alice", "age": 25, "city": "New York"}

# Modifying an existing value
person["age"] = 30
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Adding a new key-value pair
person["country"] = "USA"
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'country': 'USA'}

In this example:

The value for the key “age” is updated to 30, and a new key-value pair “country”: “USA” is added to the dictionary.

4. Removing Elements from a Dictionary

You can remove elements from a dictionary using pop(), popitem(), or del.

Example: Removing Elements Using pop()

The pop() method removes the specified key and returns its value.

# Example: Removing an element using pop()
person = {"name": "Alice", "age": 25, "city": "New York"}
age = person.pop("age")
print(age)  # Output: 25
print(person)  # Output: {'name': 'Alice', 'city': 'New York'}

In this example:

pop(“age”) removes the key “age” and returns its value (25).

Example: Removing the Last Item Using popitem()

The popitem() method removes and returns the last inserted key-value pair.

# Example: Removing the last item using popitem()
person = {"name": "Alice", "age": 25, "city": "New York"}
item = person.popitem()
print(item)  # Output: ('city', 'New York')
print(person)  # Output: {'name': 'Alice', 'age': 25}

In this example:

popitem() removes and returns the last inserted key-value pair.

Example: Removing Elements Using del

The del statement can be used to remove a key-value pair from the dictionary.

# Example: Removing an element using del
person = {"name": "Alice", "age": 25, "city": "New York"}
del person["city"]
print(person)  # Output: {'name': 'Alice', 'age': 25}

In this example:

del person[“city”] removes the key “city” and its corresponding value.

Example: Clearing a Dictionary

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

# Example: Clearing a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
person.clear()
print(person)  # Output: {}

In this example:

clear() removes all key-value pairs from the dictionary.

5. Dictionary Keys, Values, and Items

You can get all the keys, values, or key-value pairs from a dictionary using the keys(), values(), and items() methods.

Example: Getting Keys, Values, and Items

# Example: Getting keys, values, and items
person = {"name": "Alice", "age": 25, "city": "New York"}

# Getting all keys
print(person.keys())  # Output: dict_keys(['name', 'age', 'city'])

# Getting all values
print(person.values())  # Output: dict_values(['Alice', 25, 'New York'])

# Getting all key-value pairs
print(person.items())  # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

In this example:

keys() returns all the keys in the dictionary.
values() returns all the values.
items() returns a list of tuples, where each tuple contains a key-value pair.

6. Iterating Over a Dictionary

You can iterate over the keys, values, or key-value pairs of a dictionary using a for loop.

Example: Iterating Over Keys

# Example: Iterating over keys
person = {"name": "Alice", "age": 25, "city": "New York"}

for key in person:
    print(key)

# Output:
# name
# age
# city

Example: Iterating Over Values

# Example: Iterating over values
for value in person.values():
    print(value)

# Output:
# Alice
# 25
# New York

Example: Iterating Over Key-Value Pairs

# Example: Iterating over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

# Output:
# name: Alice
# age: 25
# city: New York

In these examples:

You can loop through the dictionary by keys, values, or key-value pairs using items().

7. Checking if a Key Exists in a Dictionary

You can check if a key exists in a dictionary using the in keyword.

Example: Checking if a Key Exists

# Example: Checking if a key exists in a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

print("name" in person)  # Output: True
print("country" in person)  # Output: False

In this example:

The in keyword checks whether a key exists in the dictionary (True or False).

8. Dictionary Comprehension

You can create dictionaries using dictionary comprehension, similar to list comprehension.

Example: Dictionary Comprehension

# Example: Dictionary comprehension to create a dictionary of squares
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example:

A dictionary is created where the keys are numbers from 1 to 5, and the values are the squares of the keys.

9. Merging Dictionaries

You can merge two dictionaries using the update() method or the | operator (available in Python 3.9+).

Example: Merging Dictionaries Using update()

# Example: Merging dictionaries using update()
person = {"name": "Alice", "age": 25}
address = {"city": "New York", "country": "USA"}

person.update(address)
print(person)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

Example: Merging Dictionaries Using | Operator (Python 3.9+)

# Example: Merging dictionaries using | operator
person = {"name": "Alice", "age": 25}
address = {"city": "New York", "country": "USA"}

merged_dict = person | address
print(merged_dict)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

In this example:

update() adds the key-value pairs from address to person.
The | operator merges two dictionaries into a new one (available in Python 3.9 and later).

10. Copying a Dictionary

You can create a shallow copy of a dictionary using the copy() method.

Example: Copying a Dictionary

# Example: Copying a dictionary
person = {"name": "Alice", "age": 25}
person_copy = person.copy()
print(person_copy)  # Output: {'name': 'Alice', 'age': 25}

In this example:

copy() creates a shallow copy of the person dictionary.

11. Nested Dictionaries

A dictionary can contain another dictionary as a value, creating nested dictionaries.

Example: Nested Dictionaries

# Example: Nested dictionary
people = {
    "person1": {"name": "Alice", "age": 25},
    "person2": {"name": "Bob", "age": 30}
}

print(people["person1"]["name"])  # Output: Alice

In this example:

The dictionary people contains two nested dictionaries, and you can access the inner dictionary values using multiple keys.

Summary

A dictionary in Python is an unordered collection of key-value pairs where each key is unique.
You can create, modify, remove, and access dictionary elements using keys.
Dictionary operations include getting keys, values, and items, as well as performing set-like operations such as merging.
Dictionary comprehension offers a concise way to create dictionaries.
You can work with nested dictionaries to store complex data structures.

By mastering Python dictionaries, you can efficiently manage and process data that involves key-value pairs, making your programs more organized and readable.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More