Python Dictionary Data Structure

A Python dictionary is an unordered collection of key-value pairs. Dictionaries are mutable, meaning they can be changed after they are created. They are ideal for storing data that needs to be accessed via unique keys.

Here are some common use cases for dictionaries:

  • Data Storage with Keys: Store data using unique keys.
  • Efficient Lookups: Dictionaries allow fast access to data using keys.
  • Mapping Relationships: Use dictionaries to map one value to another, like names to ages.
  • Storing Structured Data: Store complex data structures, such as nested dictionaries or lists, using dictionaries.


What You'll Learn

In this tutorial, you'll learn how to create, access, and manipulate Python dictionaries. We'll explore basic operations, examples, and how dictionaries differ from lists and tuples.


Understanding the dictionary Data Structure

The basic syntax for creating a dictionary is as follows:

python
dict_example = {"name": "John", "age": 30, "city": "New York"}
  • dict_example: This is the name of the dictionary variable.
  • { "name": "John", "age": 30, "city": "New York" }: The key-value pairs are enclosed in curly braces. Each pair consists of a key (e.g., "name") and its associated value (e.g., "John").

Dictionaries are unordered, meaning they don't store items in a specific order, unlike lists and tuples.


Creating a Dictionary

In Python, dictionaries are created using curly braces . Each key-value pair is separated by a colon, and pairs are separated by commas. Here are a few common ways to create dictionaries:

1. Defining a Dictionary with Values

You can create a dictionary by directly specifying the key-value pairs inside curly braces.

python
my_dict = {"name": "Tom", "age": 25, "city": "Wonderland"}

2. Using the dict() Constructor

You can also create a dictionary using the dict() constructor with a list of key-value tuples.

python
my_dict = dict(name="Tom", age=25, city="Wonderland")

3. Creating an Empty Dictionary

An empty dictionary can be created using empty curly braces or the dict() constructor.

python
empty_dict = {}

Accessing Dictionary Elements

In Python, you can access the values in a dictionary using the associated key. There are several ways to access dictionary elements depending on your needs. Here are the most common methods:

1. Accessing with Square Brackets

The most straightforward way to access a value in a dictionary is by using square brackets dictionary[key]. If the key exists, it returns the value associated with that key.

python
person = {"name": "Tom", "age": 30, "city": "New York"}

# Accessing values using square brackets
print(person["name"])  # Output: Tom
print(person["age"])   # Output: 30

In the example above, we accessed the values of the "name" and "age" keys using square brackets.

2. Accessing with the get() Method

You can also use the get() method to access dictionary elements. This method is helpful because it does not raise an error if the key does not exist. Instead, it returns None (or a specified default value if provided).

python
# Using get() to access values
person = {"name": "Tom", "age": 30, "city": "New York"}

print(person.get("name"))  # Output: Tom
print(person.get("age"))   # Output: 30
print(person.get("job"))   # Output: None (key "job" does not exist)

The get() method is especially useful when you are not sure if a key exists in the dictionary. You can also provide a default value to return if the key is not found.

python
# Using get() with a default value
print(person.get("job", "Not Available"))  # Output: Not Available

3. Accessing with keys(), values(), and items()

You can access all keys, values, or key-value pairs in a dictionary using the following methods:

  • keys(): Returns all the keys in the dictionary.
  • values(): Returns all the values in the dictionary.
  • items(): Returns all key-value pairs as tuples.
python
person = {"name": "Tom", "age": 30, "city": "New York"}

# Accessing keys, values, and items
print(person.keys())   # Output: dict_keys(['name', 'age', 'city'])
print(person.values()) # Output: dict_values(['Tom', 30, 'New York'])
print(person.items())  # Output: dict_items([('name', 'Tom'), ('age', 30), ('city', 'New York')])

You can also loop through these returned objects to access individual elements. Here’s how you can use them in a loop:

python
# Looping through dictionary items
for key, value in person.items():
    print(f"{key}: {value}")

This will output each key-value pair in the dictionary:

python
name: Tom
age: 30
city: New York

4. Accessing Nested Dictionaries

Sometimes, dictionaries contain other dictionaries as values. These are called nested dictionaries. You can access the elements of a nested dictionary by chaining the keys.

python
person = {
    "name": "Tom",
    "age": 30,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    }
}

# Accessing nested dictionary values
print(person["address"]["city"])  # Output: New York

In the example above, we accessed the "city" value within the nested "address" dictionary.

5. Handling Missing Keys

If you attempt to access a key that does not exist using square brackets, it will raise a KeyError. To avoid this, you can use get() or check if the key exists using the in keyword.

python
person = {"name": "Tom", "age": 30}

# Accessing with square brackets (raises KeyError)
# print(person["job"])  # KeyError: 'job'

# Accessing with get() (returns None)
print(person.get("job"))  # Output: None

# Checking if key exists
if "job" in person:
    print(person["job"])
else:
    print("Key 'job' not found!")  # Output: Key 'job' not found!

Modifying a Python Dictionary

Once a dictionary is created, you can modify its values. You can either update the value of an existing key or add a new key-value pair to the dictionary.

1. Updating an Existing Key-Value Pair

To update the value associated with an existing key, you simply assign a new value to that key. Here's how you can modify the age of a person in a dictionary:

python
person = {"name": "Tom", "age": 25, "city": "New York"}
# Modifying the 'age' value
person["age"] = 26

How It Works:

  • person["age"] = 26: This line updates the value associated with the key "age" to 26.
  • If the key exists, its value will be replaced with the new value. If the key doesn't exist, a new key-value pair will be added.

Output

{'name': 'Tom', 'age': 26, 'city': 'New York'}

2. Adding a New Key-Value Pair

You can also add new key-value pairs to an existing dictionary. If a key doesn't exist in the dictionary, it will be created with the specified value. Here's how you can add a new key for the "email" of the person:

python
person["email"] = "Tom@example.com"

How It Works:

  • person["email"] = "Tom@example.com": This adds a new key "email" with the value "Tom@example.com" to the dictionary.
  • If the "email" key didn't exist, this line will create it. If it already existed, it would overwrite the existing value.

Output

{'name': 'Tom', 'age': 26, 'city': 'New York', 'email': 'Tom@example.com'}

3. Removing a Key-Value Pair

You can also remove key-value pairs from a dictionary using the del statement. For example, to remove the "city" key from the dictionary:

python
del person["city"]

How It Works:

  • del person["city"]: This line removes the key-value pair where the key is "city".
  • If the key doesn't exist, Python will raise a KeyError, so it's a good idea to check if the key exists before deleting it.

Output

{'name': 'Tom', 'age': 26, 'email': 'Tom@example.com'}

4. Using the pop() Method to Remove Items

Another way to remove a key-value pair is by using the pop() method. This method removes the item with the specified key and returns its value. Here's how you can use it:

python
# Removing 'age' using pop
removed_value = person.pop("age")

How It Works:

  • person.pop("age"): This removes the key-value pair for "age" and assigns its value to removed_value.
  • If the key doesn't exist, Python will raise a KeyError, unless a default value is provided to pop().

Output

Removed value: 26
{'name': 'Tom', 'city': 'New York', 'email': 'Tom@example.com'}

You can also specify a default value when using pop() to avoid a KeyError:

python
removed_value = person.pop("phone", "No phone number")

How It Works:

  • If the "phone" key is not found, "No phone number" will be returned as the default value.
  • This prevents Python from raising an error if the key is missing.

Output

Removed value: No phone number
{'name': 'Tom', 'city': 'New York', 'email': 'Tom@example.com'}

Dictionary Methods

MethodDescription
clear()Removes all items from the dictionary, leaving it empty.
Ex: my_dict.clear()
copy()Returns a shallow copy of the dictionary (does not affect the original dictionary).
Ex: my_dict_copy = my_dict.copy()
get()Returns the value associated with the given key, or null if the key doesn't exist.
Ex: my_dict.get("name")
items()Returns a view object that displays a list of dictionary's key-value tuple pairs.
Ex: my_dict.items()
keys()Returns a view object that displays a list of all keys in the dictionary.
Ex: my_dict.keys()
pop()Removes and returns the value of the specified key. Raises a KeyError if the key doesn't exist.
Ex: my_dict.pop("name")
popitem()Removes and returns the last key-value pair from the dictionary.
Ex: my_dict.popitem()
setdefault()Returns the value of the key if it exists, otherwise sets it with the specified default value.
Ex: my_dict.setdefault("name", "Tom")
update()Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.
Ex: my_dict.update({"age": 30})
values()Returns a view object that displays a list of all values in the dictionary.
Ex: my_dict.values()
fromkeys()Creates a new dictionary with keys from an iterable and values set to a default.
Ex: my_dict.fromkeys(["name", "age"], "Unknown")
delDeletes the specified key and its associated value from the dictionary.
Ex: del my_dict["age"]
len()Returns the length of the dictionary.
Ex: len(my_dict)

Dictionary Methods in Python:

python

my_dict = {'name': 'Tom', 'age': 25, 'city': 'New York'}

# Example 1: clear()
my_dict.clear()  # Removes all items from the dictionary
print(my_dict)  # Output: {}

# Example 2: copy()
my_dict_copy = my_dict.copy()  # Returns a shallow copy of the dictionary
print(my_dict_copy)  # Output: {'name': 'Tom', 'age': 25, 'city': 'New York'}

# Example 3: get()
name = my_dict.get("name")  # Returns the value for the key 'name'
print(name)  # Output: Tom

# Example 4: items()
items = my_dict.items()  # Returns a view object of key-value pairs
print(items)  # Output: dict_items([('name', 'Tom'), ('age', 25), ('city', 'New York')])

# Example 5: keys()
keys = my_dict.keys()  # Returns a view object of dictionary keys
print(keys)  # Output: dict_keys(['name', 'age', 'city'])

# Example 6: pop()
removed_value = my_dict.pop("age")  # Removes the key 'age' and returns its value
print(removed_value)  # Output: 25
print(my_dict)  # Output: {'name': 'Tom', 'city': 'New York'}

# Example 7: popitem()
removed_item = my_dict.popitem()  # Removes and returns the last inserted key-value pair
print(removed_item)  # Output: ('city', 'New York')
print(my_dict)  # Output: {'name': 'Tom'}

# Example 8: setdefault()
my_dict.setdefault("name", "Bob")  # Returns the value of 'name', or sets it if not present
print(my_dict)  # Output: {'name': 'Tom'}  # No change because 'name' already exists
my_dict.setdefault("age", 30)  # Adds 'age' with value 30 because 'age' is not in the dictionary
print(my_dict)  # Output: {'name': 'Tom', 'age': 30}

# Example 9: update()
my_dict.update({"city": "Los Angeles", "country": "USA"})  # Updates the dictionary with new key-value pairs
print(my_dict)  # Output: {'name': 'Tom', 'age': 30, 'city': 'Los Angeles', 'country': 'USA'}

# Example 10: values()
values = my_dict.values()  # Returns a view object of dictionary values
print(values)  # Output: dict_values(['Tom', 30, 'Los Angeles', 'USA'])

# Example 11: fromkeys()
new_dict = {}.fromkeys(["name", "age"], "Unknown")  # Creates a new dictionary with specified keys
print(new_dict)  # Output: {'name': 'Unknown', 'age': 'Unknown'}

# Example 12: del
del my_dict["city"]  # Deletes the key-value pair for 'city'
print(my_dict)  # Output: {'name': 'Tom', 'age': 30, 'country': 'USA'}

# Example 13: len()
print(len(my_dict))  # Output: 3 (number of key-value pairs in the dictionary)

Frequently Asked Questions

What is a dictionary in Python?

A dictionary is a built-in Python data type that stores data in key-value pairs. It’s unordered and mutable, making it great for structured data.


How do you create a dictionary in Python?

Use curly braces and colons to define key-value pairs. Example: my_dict = {'name': 'Tom', 'age': 25}.


Can dictionary keys be of any data type?

Keys must be immutable types (like strings, numbers, or tuples). Values, however, can be any data type.


How do you access or modify a dictionary value?

Access values using the key: my_dict['name']. Modify by assigning a new value: my_dict['name'] = 'Bob'.


What are common dictionary methods in Python?

Dictionaries support methods like get(), keys(), values(), items(), pop(), and update().



What's Next?

Next, you'll explore sets in Python, an unordered collection of unique elements. Understanding how sets differ from dictionaries will help you choose the right data structure based on your needs.