How to initialize a dictionary in Python

Learn how to initialize a dictionary in Python. Explore different methods, tips, real-world applications, and how to debug common errors.

How to initialize a dictionary in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

Dictionary initialization is a core skill in Python for structuring data. You can create dictionaries using curly braces {} or the dict() constructor for flexible key-value pair management.

You'll explore several initialization techniques, each with practical tips. You'll also find real-world applications and debugging advice to help you select the best approach for your use case.

Creating a dictionary with curly braces {}

student = {"name": "John", "age": 21, "courses": ["Math", "Science"]}
print(student)--OUTPUT--{'name': 'John', 'age': 21, 'courses': ['Math', 'Science']}

Using curly braces {} is the most direct and readable way to initialize a dictionary when you know the contents upfront. This approach, known as creating a dictionary literal, is highly efficient for static data.

The student example showcases a key strength of Python dictionaries: value flexibility. Notice how different data types are used for the values:

  • The key "name" is mapped to a string.
  • The key "age" is mapped to an integer.
  • The key "courses" is mapped to a list of strings.

Basic dictionary initialization methods

Beyond the straightforward curly brace approach, Python offers more dynamic methods like the dict() constructor, dict.fromkeys(), and dictionary comprehensions for different scenarios.

Using the dict() constructor

student = dict(name="John", age=21, courses=["Math", "Science"])
print(student)--OUTPUT--{'name': 'John', 'age': 21, 'courses': ['Math', 'Science']}

The dict() constructor offers a clean alternative, especially when your keys are simple strings. It works by treating keyword arguments—like name="John"—as key-value pairs. This approach is often preferred for its readability when keys are valid Python identifiers.

  • The keyword name automatically becomes the string key "name", so you don't need to wrap it in quotes.
  • This makes it a great choice when your keys don't contain spaces or special characters, resulting in less visual clutter.

Using dict.fromkeys() method

keys = ["name", "age", "grade"]
student = dict.fromkeys(keys, "Unknown")
print(student)--OUTPUT--{'name': 'Unknown', 'age': 'Unknown', 'grade': 'Unknown'}

The dict.fromkeys() method is a handy shortcut for creating a dictionary where multiple keys share the same initial value. It takes an iterable of keys—in this case, the keys list—and assigns a single default value to all of them.

  • You can see how each key from the list is mapped to the default value "Unknown".
  • This approach is perfect for creating a template or placeholder dictionary before you have the final data to populate it.

Using dictionary comprehension

names = ["John", "Emma", "Alex"]
scores = [85, 92, 78]
student_scores = {name: score for name, score in zip(names, scores)}
print(student_scores)--OUTPUT--{'John': 85, 'Emma': 92, 'Alex': 78}

Dictionary comprehensions offer a concise and powerful way to build dictionaries from existing iterables. In this example, the zip() function pairs each name from the names list with a corresponding score from the scores list.

  • The comprehension then iterates through these pairs, assigning each name as a key and its score as the value.
  • This method is highly efficient for transforming and combining data into a new dictionary on the fly.

Advanced dictionary initialization techniques

With the fundamentals covered, you can now tackle more complex scenarios like merging dictionaries with the | operator, creating nested structures, and using defaultdict.

Merging dictionaries with the | operator

personal_info = {"name": "John", "age": 21}
academic_info = {"major": "Computer Science", "GPA": 3.8}
student = personal_info | academic_info # Python 3.9+ syntax
print(student)--OUTPUT--{'name': 'John', 'age': 21, 'major': 'Computer Science', 'GPA': 3.8}

The pipe operator | is a clean, modern way to merge two dictionaries. Introduced in Python 3.9, it combines the key-value pairs from both into a single new dictionary. This approach is highly readable and leaves the original dictionaries—personal_info and academic_info—unchanged.

  • It’s important to know that if both dictionaries share a key, the value from the right-hand dictionary will be used in the final result.

Creating nested dictionaries

students = {
"John": {"age": 21, "courses": ["Math", "Science"]},
"Emma": {"age": 20, "courses": ["History", "English"]}
}
print(students["John"]["courses"])--OUTPUT--['Math', 'Science']

Nested dictionaries are simply dictionaries inside other dictionaries, which is a powerful way to group related information. The students dictionary, for example, uses student names as keys, with each key mapping to another dictionary that holds that student's specific data.

  • This structure allows you to organize complex datasets cleanly.
  • To access nested values, you chain the keys together. For instance, students["John"] first gets the inner dictionary, and then ["courses"] retrieves the course list from it.

Using defaultdict for automatic initialization

from collections import defaultdict
student_grades = defaultdict(list)
student_grades["John"].append(85)
student_grades["John"].append(92)
print(dict(student_grades))--OUTPUT--{'John': [85, 92]}

The defaultdict from the collections module is a handy tool for preventing KeyError exceptions. When you initialize it with a type, like list, it automatically creates a default value for any key you try to access that doesn't exist yet. This is perfect for grouping or counting items.

  • In this example, when you first access student_grades["John"], the defaultdict creates an empty list for the key "John".
  • This lets you immediately append() values without writing extra code to check if the key already exists.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it, complete with databases, APIs, and deployment.

For the dictionary techniques you've just learned, Replit Agent can turn them into production-ready tools. You could:

  • Build a user profile generator that uses dict.fromkeys() to create new accounts with default fields.
  • Create a data mapping tool that combines lists of product IDs and prices into a single catalog using a dictionary comprehension.
  • Deploy a log processor that leverages a defaultdict to group log entries by severity level for quick analysis.

Bring your app idea to Replit Agent, and it will write the code, handle testing, and deploy your application automatically.

Common errors and challenges

Even with the right initialization method, you might run into a few common pitfalls when working with dictionaries in Python.

  • Avoiding KeyError: A KeyError occurs when you try to access a key that doesn't exist. Instead of letting your program crash, you can use the get() method. It safely retrieves a key's value and returns None—or a default value you specify—if the key isn't found.
  • Modifying during iteration: Changing a dictionary's size while looping over it will trigger a RuntimeError. To avoid this, iterate over a copy. You can create a static list of keys with list(my_dict.keys()) before starting your loop, which prevents the error.
  • Using immutable keys: Dictionary keys must be of an immutable type, meaning they cannot be changed. This is why strings, numbers, and tuples work as keys, but lists and other dictionaries don't. Attempting to use a mutable key will result in a TypeError because the dictionary relies on a key's stable hash value to operate efficiently.

Avoiding KeyError when accessing non-existent dictionary keys

A KeyError is one of the most common issues you'll face. It happens when you try to access a key that doesn't exist in the dictionary, which immediately stops your program. The code below shows what happens when you look for "Alex".

student_scores = {"John": 85, "Emma": 92}
print(student_scores["Alex"]) # This will raise KeyError: 'Alex'

The code fails because the key "Alex" doesn't exist in the student_scores dictionary, which only contains entries for "John" and "Emma". The following example demonstrates a safer way to access keys that might be missing.

student_scores = {"John": 85, "Emma": 92}
print(student_scores.get("Alex", "Not found"))

The get() method provides a safe way to access dictionary keys. Instead of crashing, it returns a default value if the key isn't found. In the example, student_scores.get("Alex", "Not found") looks for the key "Alex". Since it doesn't exist, the method returns the string "Not found" instead of raising a KeyError. It's especially useful when you're working with data where some keys might be missing.

Avoiding errors when modifying a dictionary during iteration

It’s tempting to remove items from a dictionary while you’re looping through it, but this will crash your program with a RuntimeError. Python doesn’t allow changing a dictionary’s size during iteration because it can cause unpredictable behavior. The code below shows this error in action.

scores = {"John": 65, "Emma": 45, "Alex": 90}
for name, score in scores.items():
if score < 50:
del scores[name] # RuntimeError: dictionary changed size during iteration
print(scores)

The code fails because it attempts to modify the scores dictionary with del scores[name] while iterating over it. Python prohibits changing a dictionary's size mid-loop. The following example demonstrates a safe way to handle this.

scores = {"John": 65, "Emma": 45, "Alex": 90}
passing_scores = {name: score for name, score in scores.items() if score >= 50}
print(passing_scores)

The best way to filter a dictionary is to build a new one. This example uses a dictionary comprehension to create passing_scores. It iterates through the original scores.items() and includes only the pairs where the score is 50 or higher. This completely avoids the RuntimeError because the original dictionary is never changed during the loop. It’s a clean, Pythonic solution for creating a filtered copy of your data.

Using immutable types as dictionary keys

Python dictionaries require keys to be immutable, like strings or numbers, because they rely on a stable hash value for fast lookups. Using a mutable type, such as a list, breaks this rule and will cause a TypeError, as the following code demonstrates.

student_grades = {}
courses = ["Math", "Science"]
student_grades[courses] = [85, 92] # TypeError: unhashable type: 'list'
print(student_grades)

This code triggers a TypeError because it uses the courses list as a key. Dictionaries require keys that are unchangeable, and lists don't fit that rule. The example below shows how to correctly structure this.

student_grades = {}
courses = ("Math", "Science") # Using immutable tuple instead of list
student_grades[courses] = [85, 92]
print(student_grades)

The fix is to convert the list into a tuple. By changing the key to ("Math", "Science"), the code works because tuples are immutable. Unlike lists, their contents can't be changed, which gives them a stable hash value required by dictionaries. This is why you'll often see strings, numbers, or tuples used as keys. Keep an eye out for this TypeError whenever you're creating complex keys from other data structures.

Real-world applications

With a handle on common errors, you can now apply these dictionary techniques to practical tasks like counting item frequencies and caching data.

Creating a frequency counter with dict.get()

The get() method is perfect for building frequency counters because it elegantly handles both initializing a new item's count and incrementing an existing one in a single, readable line.

text = "apple banana apple orange banana apple"
word_count = {}
for word in text.split():
word_count[word] = word_count.get(word, 0) + 1
print(word_count)

This code builds a dictionary to count word frequencies from a string. The loop processes each word from the text after it's split into a list. The core of the logic is the expression word_count.get(word, 0), which ensures there's always a number to work with.

  • When a word appears for the first time, get() returns 0.
  • For words that are already in the dictionary, it returns their current count.

The code then adds 1 to that number and updates the dictionary, creating a concise frequency counter.

Implementing a simple memoization cache with dictionaries

A dictionary is an excellent tool for implementing a memoization cache, a technique that speeds up your code by storing the results of expensive function calls so you don't have to compute them more than once.

cache = {}

def calculate_expensive_value(x):
if x in cache:
return f"From cache: {cache[x]}"
result = x * x * x # Simulate expensive calculation
cache[x] = result
return f"Calculated: {result}"

print(calculate_expensive_value(5))
print(calculate_expensive_value(5)) # Second call uses cache

This code shows how a dictionary can store and retrieve computed values. The calculate_expensive_value function first checks if an input x already exists as a key in the cache dictionary.

  • If the key is found, the function returns the stored value, skipping the calculation.
  • If the key is not found, it computes the result, adds it to the cache, and then returns it.

This way, the first time you call the function with 5, it performs the calculation. The second call instantly retrieves the result from the cache instead.

Get started with Replit

Put your new skills to work with Replit Agent. Describe a tool like, “a script that counts word frequencies in a text file,” or “an app that merges two user lists into a single dictionary.”

Replit Agent will write the code, test for errors, and deploy your application. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.