Table of Contents

What Will You Learn
In this tutorial, you'll explore Python dictionaries, understanding their structure as key-value pairs. You'll learn how to create dictionaries, access and modify their contents, and utilize built-in methods for efficient data handling. The guide covers advanced topics like nested dictionaries and iteration techniques, equipping you with the skills to manage complex data structures in Python.


Dictionaries are one of the most important and powerful data structures in Python. They allow you to store, access, and manipulate data using key-value pairs, making them ideal for structured information. From configuration files to JSON data and API responses — dictionaries are everywhere.

Understanding how to use dictionaries effectively will give you a huge advantage when building real-world applications. Whether you're managing user profiles, counting word frequencies, or mapping IDs to values, dictionaries help you work efficiently and clearly. They provide fast lookups, flexible storage, and clean code structure.

For a beginner, learning how to define, access, update, and iterate over dictionaries is a must. Without mastering this data type, you'll struggle to process and organize even moderately complex datasets. If you're serious about learning Python, dictionaries are non-negotiable.

What Is a Dictionary in Python?

A dictionary in Python is a built-in data type used to store data in key-value pairs. Each key in a dictionary must be unique and immutable (like a string, number, or tuple), while the values can be of any type. Dictionaries are defined using curly braces {} and pairs separated by colons. This structure allows you to quickly look up values by referencing their keys.

Dictionaries are highly flexible and used in a variety of contexts such as databases, caching systems, data transformation, and configuration management. They offer constant-time access to values, making them faster than lists when retrieving specific data by label. Python also includes many built-in methods to manage and manipulate dictionaries easily.

Here are two examples that demonstrate how dictionaries work:


    # Example 1: Basic dictionary
    person = {"name": "Alice", "age": 30, "role": "admin"}
    print(person["name"])  # Output: Alice

    # Example 2: Dictionary with different types
    inventory = {"apples": 10, "bananas": 5, "in_stock": True}
    print(inventory["in_stock"])  # Output: True

How to Add to a Dictionary in Python?

Adding a new key-value pair to a dictionary is simple — just use square bracket notation with the new key and assign a value. If the key doesn’t exist, Python will automatically add it to the dictionary. This makes it easy to update data on the fly. You can also use the update() method to add multiple pairs at once. Both methods are efficient and widely used. Below are two examples.


    # Example 1: Add a single key-value pair
    user = {"name": "Bob"}
    user["age"] = 25

    # Example 2: Add multiple pairs using update()
    user.update({"role": "user", "verified": True})

How to Iterate Through a Dictionary in Python?

To iterate through a dictionary in Python, you can use a for loop combined with built-in methods like .items(), .keys(), or .values(). The .items() method is the most common because it gives you both the key and the value in each iteration. This is useful when you want to process or print complete records.

If you only need keys or values, use .keys() or .values() respectively. This approach is simple, clean, and widely used in real applications.

Below are two examples.


    # Example 1: Iterate through keys and values
    person = {"name": "Alice", "age": 30}
    for key, value in person.items():
        print(f"{key}: {value}")

    # Example 2: Iterate only through values
    for value in person.values():
        print("Value:", value)

How to Sort a Dictionary in Python?

Dictionaries themselves are unordered before Python 3.7, but you can sort them based on keys or values using the sorted() function. The result is typically a list of tuples, which you can convert back to a dictionary if needed. Sorting by keys is useful for readability, while sorting by values is useful for analytics. Always use the items() method when sorting to access both key and value pairs. Below are two examples — sorting by keys and sorting by values.


    # Example 1: Sort dictionary by keys
    data = {"b": 2, "a": 3, "c": 1}
    sorted_by_keys = dict(sorted(data.items()))
    print(sorted_by_keys)  # {'a': 3, 'b': 2, 'c': 1}

    # Example 2: Sort dictionary by values
    sorted_by_values = dict(sorted(data.items(), key=lambda item: item[1]))
    print(sorted_by_values)  # {'c': 1, 'b': 2, 'a': 3}

How to Append to a Dictionary in Python?

Appending to a dictionary means adding a new key-value pair or updating an existing key with a new value. You do this by assigning a value to a key using square brackets. If the key already exists, its value will be updated; if it doesn’t, the key-value pair will be added. For appending multiple values under one key, use a list as the value and then call append() on that list. This is useful when grouping related data under a single label. Here are two examples.


    # Example 1: Append a new key-value pair
    profile = {"name": "John"}
    profile["email"] = "This email address is being protected from spambots. You need JavaScript enabled to view it."

    # Example 2: Append a value to a list inside a dictionary
    grades = {"math": [90, 85]}
    grades["math"].append(95)

How to Sort a Dictionary by Value in Python?

Sorting a dictionary by value in Python is done using the sorted() function with a custom key. You access key-value pairs with .items() and apply a lambda function that targets the value. The result is a sorted list of tuples, which you can convert back into a dictionary using dict(). This is useful when ranking scores, analyzing data, or organizing items by frequency. You can sort in ascending or descending order using the reverse parameter. Below are two examples.


    # Example 1: Sort by value (ascending)
    scores = {"Alice": 88, "Bob": 95, "Charlie": 70}
    sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1]))
    print(sorted_scores)  # {'Charlie': 70, 'Alice': 88, 'Bob': 95}

    # Example 2: Sort by value (descending)
    sorted_desc = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
    print(sorted_desc)  # {'Bob': 95, 'Alice': 88, 'Charlie': 70}

Common Beginner Mistakes

Accessing a Non-Existent Key

A common mistake is trying to access a key that doesn’t exist in the dictionary. This raises a KeyError, which can crash your program. Beginners often assume all keys will always be present. To avoid this, use the .get() method which returns None (or a default value) if the key is missing. This makes your code safer and easier to debug.


    # Problem
    data = {"name": "Alice"}
    print(data["age"])  # KeyError

    # Solution
    print(data.get("age", "Not found"))  # Output: Not found

Using Mutable Keys

In Python, dictionary keys must be immutable. Trying to use a list or another dictionary as a key will raise a TypeError. Beginners often attempt this without realizing that only hashable objects (like strings, numbers, or tuples) are allowed. Always make sure that keys are of a valid type.


    # Problem
    my_dict = {[1, 2]: "value"}  # TypeError: unhashable type: 'list'

    # Solution
    my_dict = {(1, 2): "value"}  # Tuples are immutable and valid

Overwriting Existing Keys by Mistake

If you assign a value to a key that already exists, it will silently overwrite the old value. This can lead to data loss if you're not careful. It's especially common when dynamically building dictionaries. To prevent this, check if the key exists before assigning, or use setdefault() when initializing keys.


    # Problem
    scores = {"Alice": 90}
    scores["Alice"] = 85  # Overwrites the original value

    # Solution
    if "Alice" not in scores:
        scores["Alice"] = 85

Confusing Keys and Values During Iteration

Beginners sometimes confuse keys with values when looping over a dictionary. Using for item in dict only gives the keys. If you need both the key and the value, you must use .items(). Otherwise, your logic might fail or produce unexpected results.


    # Problem
    my_dict = {"a": 1, "b": 2}
    for item in my_dict:
        print(item)  # Only prints keys

    # Solution
    for key, value in my_dict.items():
        print(key, value)

Assuming Dictionary Order Is Fixed

Before Python 3.7, dictionaries did not guarantee insertion order. Relying on that order for logic or output was a common beginner error. Although modern Python keeps insertion order, you should still avoid depending on it unless necessary. If your logic requires order, sort the dictionary explicitly or use collections.OrderedDict for older versions.


    # Problem (older Python versions)
    d = {"b": 2, "a": 1}
    print(list(d))  # Output order is unpredictable before 3.7

    # Solution
    for key in sorted(d):
        print(key, d[key])

Frequently Asked Questions (FAQ)

How to check if a dictionary is empty in Python?

To check if a dictionary is empty in Python, you can use a simple boolean check: if not my_dict:. An empty dictionary is treated as False in a conditional statement, so this check is clean and readable. If the dictionary has at least one key-value pair, it will evaluate to True. You can also explicitly check the length using len(my_dict) == 0, but that is more verbose.


      # Using boolean check
      my_dict = {}
      if not my_dict:
          print("Dictionary is empty")

      # Using len()
      if len(my_dict) == 0:
          print("Still empty")

This check is useful when validating inputs, initializing data, or controlling flow based on whether the dictionary contains values.

Can you sort a dictionary in Python?

Yes, you can sort a dictionary in Python, but dictionaries themselves are not inherently sorted. When you "sort" a dictionary, you typically sort its items and return them as a list of tuples or a new dictionary. You can sort by keys or values using the sorted() function and a lambda function as the key parameter. If you want to preserve the sorted order, wrap the result in dict() or use collections.OrderedDict in older versions of Python.


      # Sort by keys
      data = {"b": 2, "a": 3}
      sorted_by_keys = dict(sorted(data.items()))

      # Sort by values
      sorted_by_values = dict(sorted(data.items(), key=lambda x: x[1]))

Sorting a dictionary helps with display, analytics, or structured processing.

How to loop through a dictionary in Python?

You can loop through a dictionary using a for loop in combination with its built-in methods like .items(), .keys(), and .values(). The most common approach is using .items(), which gives access to both the key and value in each iteration. This is helpful when you need to process or print the entire content. If you only need keys or values, use .keys() or .values() accordingly.


      my_dict = {"name": "Alice", "age": 30}

      # Loop through keys and values
      for key, value in my_dict.items():
          print(f"{key}: {value}")

      # Loop through values only
      for val in my_dict.values():
          print(val)

These looping methods are clean and work across all Python versions.

How to update an existing key in a Python dictionary?

To update an existing key in a dictionary, assign a new value to that key using the bracket notation: my_dict[key] = new_value. If the key exists, its value will be replaced. If it doesn’t, Python will add it as a new key-value pair. You can also use the update() method to update one or more keys at once. This method is cleaner when updating multiple entries.


      # Using direct assignment
      data = {"user": "Alice"}
      data["user"] = "Bob"  # Overwrites the value

      # Using update()
      data.update({"user": "Charlie", "age": 25})

Always double-check the key before overwriting, especially in dynamic or user-generated data.

What is the difference between get() and direct access in dictionaries?

The main difference between using dict[key] and dict.get(key) lies in error handling. If you try to access a non-existent key using dict[key], Python raises a KeyError. However, dict.get(key) will return None or a default value you specify. This makes get() safer for optional or uncertain keys, especially when working with user input or external data.


      data = {"name": "Alice"}

      # Raises error
      # print(data["age"])

      # Safe alternative
      print(data.get("age", "Not provided"))

Use get() when you're unsure if the key exists and want to avoid crashing your program.