Table of Contents

What Will You Learn
You'll learn how to create, access, update, and delete key-value pairs, as well as how to use built-in methods to efficiently manage data. The guide also explains practical use cases and common pitfalls when working with dictionaries.


Working with data in a programming language goes beyond simple lists or strings. In real-world scenarios, it's often necessary to store key-value pairs, where each key is associated with a specific value: a username and their email, a product and its price, an ID and its related information. This is where a mapping comes in — a data structure that organizes information based on a “key–value” principle.

Mapping is considered one of the most versatile structures. It provides instant access to data by key, ease of modification, and logical associations between elements. A beginner developer will encounter this structure within the first weeks of learning — when working with JSON, APIs, configurations, and control logic.

Understanding the principles of mappings and how to properly use dictionaries (dict) is one of the key steps toward professional development.

What is Mapping Data Type in Python?

A mapping is a data structure where each element is a pair: a key and its associated value. A mapping has no fixed order (in Python 3.6+, order is preserved but should not be relied on), and values are accessed not by index like in a list, but by key.

The main built-in mapping type is dict. A dictionary is used in all types of applications: from simple scripts to user management systems. Here's a basic example:

 
  user = {
    "name": "Alice",
    "age": 30,
    "active": True
  }

In this case, user is a dictionary that stores user information. It consists of three key–value pairs:

Each key ("name", "age", "active") has a corresponding value. Keys must be unique and immutable (str, int, tuple), and values can be of any type. Working with dict helps reduce code, improve readability, and efficiently manage complex data structures.

What are the Main Characteristics of Python Mappings?

All mapping structures in Python share a number of common traits. These are what distinguish mappings from lists, strings, and other collections.

Main characteristics of mapping types:

  • Stores key–value pairs. Each element consists of two linked parts: a key and a value. This logically connects the data.
  • Fast access by key. Values can be retrieved instantly using a known key: user["name"].
  • Keys must be immutable. Allowed types include str, int, bool, tuple. list or dict cannot be used as keys.
  • Values can be of any type. They can be numbers, strings, lists, other dictionaries, or even functions.
  • Dynamically modifiable content. You can add, change, or remove key–value pairs at any time.
  • Key existence check with inA convenient way to check if a key exists: "email" in user.
  • Safe access with the .get() method. .get() helps avoid errors when accessing non-existent keys.
  • Supports iteration. You can loop through a dict by keys, values, or key–value pairs (.items()).

A mapping is not just a storage structure. It’s a flexible tool for organizing data that enables building reliable and scalable architectures within a program. The next sections will demonstrate how to create, read, and modify dictionaries in practice.

What are the Built-in Mapping Types in Python?

Although dict is the most commonly used mapping type in daily development, Python offers several other built-in mapping types. These expand the capabilities of storing and managing key–value pairs.

Main mapping types in Python

Type Description Use Cases
dict The standard built-in dictionary. Stores key–value pairs. Fast access, supports all operations, used in most scenarios
collections.defaultdict A dictionary with auto-initialized default values. Useful for counters, grouping, aggregating data by keys
collections.ChainMap Combines multiple dictionaries into a single logical structure. Ideal for configuration layering, prioritizing settings sources
types.MappingProxyType Creates a read-only view of a regular dictionary. Used to protect data from modification when passed around

This table helps you quickly navigate the available mapping types and choose the right tool for the task at hand.

In practice, 90% of use cases are solved with dict, but knowing the other types comes in handy when working with more complex structures, configuration systems, or when protection from changes is needed.

How to Create a Mapping in Python?

Creating a dictionary is one of the simplest and most frequent operations. There are several ways to do it, all of which are easy to read and maintain.

Ways to create a dictionary:

 
    # 1. Using curly braces
    person = {
        "name": "Alice",
        "age": 30
    }
    
    # 2. Using the dict() function
    user = dict(name="Bob", active=True)
    
    # 3. From a list of tuples
    pairs = [("key1", 100), ("key2", 200)]
    d = dict(pairs)
    
    # 4. Creating an empty dictionary
    empty = {}

Within a dictionary, keys must be unique and immutable. If the same key is specified more than once, the last value will be retained.

How to Access Mapping Elements?

Dictionary elements are accessed by key. There are two main ways — using square brackets and the .get() method.

Access by key:

 
  person = {"name": "Alice", "age": 30}
  print(person["name"])  # Alice

If the key is missing, a KeyError will occur.

Safe access using .get():

 
    email = person.get("email")
    print(email)  # None — no error is raised

The .get() method allows you to provide a default value:

email = person.get("email", "not provided")

This is especially useful when the data structure doesn't guarantee the presence of all keys.

How to Modify Mapping Elements?

A dictionary is a mutable structure, and you can add, update, or delete key–value pairs at any time.

Modifying a value:

person["age"] = 31

If the key exists, the value will be updated. If not, a new element will be added.

Adding a new element:

person["email"] = "This email address is being protected from spambots. You need JavaScript enabled to view it."

Removing an element:

del person["age"] 

If the key doesn't exist, an error will occur. To avoid this:

 
  if "age" in person:
    del person["age"]

Clear the entire dictionary:

person.clear()

Loop through all elements:

 
  for key, value in person.items():
    print(f"{key}: {value}")

The keys(), values(), and items() methods allow you to iterate through the respective parts of a dictionary. This is a convenient way to process data dynamically, especially when loading it from external sources (JSON, CSV, API).

Beginner Mistakes

Dictionaries are a powerful tool, but at first they may seem deceptively simple. Below are common mistakes made by beginners and ways to avoid them.

1. Accessing a Non-Existent Key

 
    user = {"name": "Alice"}
    print(user["email"])  # KeyError

Reason: the key "email" does not exist, and access via [] raises an exception.

Solution: Use the safe .get() method:

 
    print(user.get("email"))              # None
    print(user.get("email", "not found")) # not found

2. Using a Mutable Object as a Key

my_dict = {[1, 2]: "value"}  # TypeError

Reason: dictionary keys must be immutable types (str, int, tuple). Lists, dictionaries, and sets cannot be used as keys.

Solution: Use a tuple:

my_dict = {(1, 2): "value"}

3. Deleting a Non-Existent Key

 
    data = {"id": 100}
    del data["name"]  # KeyError

Reason: trying to delete a key that doesn't exist.

Solution: Check if the key exists before deleting:

 
    if "name" in data:
      del data["name"]

Or use pop() with a default value:

data.pop("name", None)

4. Unintentionally Modifying the Same Dictionary

 
    a = {"x": 1}
    b = a
    b["x"] = 999
    print(a["x"])  # 999

Reason:a and b refer to the same object in memory.

Solution: Create a copy if needed:

b = a.copy()

5. Overwriting Values with Duplicate Keys


  person = {
    "name": "Alice",
    "name": "Bob"
  }
  print(person["name"])  # Bob
  

Reason: when keys are repeated, only the last value is kept.

Solution:
Make sure your keys are unique, especially when creating dictionaries manually or generating them from data.

Avoiding these mistakes requires attention to dictionary structure, understanding behavior when accessing or modifying elements, and developing the habit of checking for keys before performing operations. Dictionaries are convenient, but require a clear understanding of how key handling works.

Frequently Asked Questions

What is the main purpose of a dictionary in Python?

A dictionary (dict) is used to store key–value pairs, where each unique key maps to a specific value. This allows fast retrieval, updating, adding, and deletion of data by name rather than by position like in a list. This structure is optimal for storing settings, user data, JSON objects, and any associative collections.

Can a dictionary key be a list or another dictionary?

No. A dictionary key must be of an immutable data type. Allowed types include: str, int, float, bool, tuple (if it contains only immutable elements). list, dict, and set are not allowed as keys — using them will raise a TypeError. This is because mutable objects do not have a consistent hash and cannot be reliably used for lookups.

How to check if a key exists in a dictionary?

Use the in operator to check for key existence:


    if "email" in user:
      print(user["email"])
    

This is the simplest and safest way to avoid a KeyError. You can also use the .get() method, which returns None (or a specified default) if the key is missing:

value = user.get("email", "not found")
What happens if you assign a new value to an existing key?

Assigning a new value to an existing key will replace the old one. The structure of the dictionary remains unchanged, only the associated value is updated:


      user = {"name": "Alice"}
      user["name"] = "Bob"
      print(user["name"])  # Bob
    

This is normal behavior and is commonly used to update settings or temporarily change a value.

How to safely remove an element from a dictionary?

It’s recommended to use the .pop() method with a default value to avoid errors when the key is missing:

user.pop("email", None)

You can also check for the key beforehand:


    if "email" in user:
      del user["email"]
    

Both approaches help prevent KeyError and make your code more resilient to incomplete data.