Python Dictionaries: Creating and Working with Keys

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Python Dictionaries: Creating and Working with Keys

Python dictionaries are one of the most powerful and convenient data structures. They store information in key-value pairs. Thanks to their flexibility and fast data access, dictionaries are widely used when working with JSON files. They are also essential for database operations and configuration handling. Dictionaries are applied in many other areas of programming.

In this guide, we'll walk through creating dictionaries in Python. We'll explore how to work with keys and values. We'll also cover popular methods and best practices.

What Is a Dictionary in Python

A dictionary is a collection that stores key-value pairs. Keys must be unique and immutable. You can use numbers, strings, or tuples as keys. Values can be any Python object.

Key characteristics of dictionaries:

  • Unordered collection (prior to Python 3.7)
  • Mutable data structure
  • Fast access to elements by key
  • Automatic key hashing
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

Dictionary Key Requirements

Dictionary keys must meet certain requirements:

  • Be immutable data types
  • Be unique within the dictionary
  • Support hashing

How to Create a Dictionary in Python

Using Curly Braces

The most common way to create a dictionary is with curly braces. This method is intuitive and widely used by developers.

car = {"brand": "Toyota", "year": 2020, "color": "white"}

Creating with the dict() Function

The dict() function provides an alternative way to create dictionaries. This approach is especially useful when building dictionaries from other data structures.

car = dict(brand="Toyota", year=2020, color="white")

Creating an Empty Dictionary

Empty dictionaries are created for later population with data. This is useful when initializing data structures.

empty_dict = {}
# or
empty_dict = dict()

Creating a Dictionary from Sequences

Dictionaries can be created from lists of tuples or other sequences:

pairs = [("name", "Anna"), ("age", 25), ("city", "San Francisco")]
person_dict = dict(pairs)

Working with Dictionary Keys

Accessing a Value by Key

To get a value by key, use square bracket syntax. Accessing a non-existent key raises a KeyError exception.

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

Safe Access with the get() Method

The get() method provides a safe way to retrieve values. If the key is missing, it returns a default value instead of raising an exception.

print(person.get("city", "City not specified"))  # Output: City not specified
print(person.get("name"))  # Output: John

Adding and Updating Values

Dictionaries support dynamic addition of new items. Assigning a value to an existing key updates the data.

person["city"] = "New York"  # Add a new key
person["age"] = 31  # Update an existing value

Removing Keys from a Dictionary

There are several ways to remove items from a dictionary:

del person["age"]  # Deletes the 'age' key and its value
removed_value = person.pop(                

Blogs

Book Recommendations