Back to Python
2026-04-195 min read

Create a Dictionary (Python Programming)

Learn Create a Dictionary (Python Programming) step by step with clear examples and exercises.

Why This Matters

In this full guide on creating dictionaries in Python, we aim to help you master the art of using dictionaries - a fundamental data structure that is essential for organizing data effectively in Python programming. By the end of this lesson, you will be able to create, manipulate, and use dictionaries with confidence.

Why This Matters

Dictionaries allow you to store key-value pairs, making it easier to access specific values using keys. This feature is particularly useful when dealing with complex data structures or large datasets as it simplifies the process of retrieving and modifying information. Moreover, dictionaries can help improve the efficiency of your code by reducing the number of variables required to store related pieces of data.

Prerequisites

To fully grasp this lesson, you should have a basic understanding of Python programming concepts such as variables, functions, loops, conditional statements, and list comprehensions. If you're new to Python or need a refresher, we recommend checking out our Python Basics course before diving into this tutorial.

Core Concept

Creating a Dictionary

A dictionary in Python is created using curly braces {}. Each key-value pair is separated by a colon (:), and pairs are separated by commas (,). Here's an example of creating a simple dictionary:

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

In this example, name, age, and city are keys, while 'John', 25, and 'New York' are their corresponding values. Keys must be unique within a dictionary, but they can be of any immutable type (strings, integers, tuples).

Accessing Dictionary Values

To access the value associated with a key, you use the key followed by square brackets []. For example:

print(my_dict['name']) # Output: John

Adding and Modifying Dictionary Entries

You can add new entries to an existing dictionary using the assignment operator (=) or the update() method. Here's how you can add a new key-value pair:

my_dict['job'] = 'Engineer' # Using assignment operator
my_dict.update({'phone': '555-1234'}) # Using update() method

Deleting Dictionary Entries

To delete a key-value pair from a dictionary, you can use the del keyword:

del my_dict['age']

Checking if a Key Exists

Before accessing a dictionary value or deleting a key-value pair, it's important to check whether a key exists in the dictionary. You can do this using the in keyword:

if 'age' in my_dict:
print(my_dict['age']) # Output: 25 (if 'age' was present before deletion)
else:
print("Key 'age' not found.")

Iterating through a Dictionary

You can iterate through the keys and values of a dictionary using the keys(), values(), and items() methods. Here are examples of each method:

for key in my_dict.keys():
print(key) # Prints all keys

for value in my_dict.values():
print(value) # Prints all values

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

Worked Example

Let's create a dictionary to store information about a student. We will add, modify, delete, and check keys in this example.

student = {
'name': 'Alice',
'age': 18,
'school': 'XYZ High School',
'grades': [90, 85, 95]
}

Add a new key-value pair

student['gender'] = 'Female'

Modify an existing value

student['age'] = 19

Delete a key-value pair

del student['school']

Check if a key exists

if 'grades' in student:

print("Student has grades.")

else:

print("Student does not have grades.")

Common Mistakes

  1. Forgetting to separate keys and values with colons (:)
  2. Using duplicate keys within a dictionary
  3. Accessing non-existent keys without checking if they exist first
  4. Trying to delete a key that does not exist in the dictionary
  5. Assuming dictionaries are ordered, when in fact Python 3.7 and later maintain insertion order
  6. Using mutable types (e.g., lists) as keys, which can lead to unexpected results when modifying the list within the dictionary

Practice Questions

  1. Create a dictionary to store information about a car (make, model, year, color). Access the values for each key.
  2. Given the following dictionary: {'apple': 5, 'banana': 4, 'orange': 3}, write code to find the fruit with the least number of items.
  3. Write a function that takes a dictionary and a key as arguments, then returns the value associated with that key if it exists; otherwise, return "Key not found."
  4. Create a dictionary to store the frequency of words in a sentence. How would you modify your code from question 3 to handle multiple occurrences of the same word?
  5. Write a function that takes two dictionaries as arguments and returns a new dictionary containing all key-value pairs from both input dictionaries. If there are duplicate keys, prioritize values from the first dictionary.

FAQ

  1. What happens when I try to add duplicate keys in a dictionary? In Python, adding duplicate keys replaces the existing value with the new one. However, if you're using an older version of Python (pre-3.7), duplicate keys are ignored.
  2. Can I iterate through the keys and values of a dictionary separately? Yes! You can use the keys(), values(), and items() methods to access the keys, values, or key-value pairs in a dictionary, respectively.
  3. How do I sort a dictionary by its keys or values? To sort a dictionary by its keys or values, you can convert them into lists using either the keys(), values(), or items() method, then use Python's built-in sorting functions (e.g., sorted()) on those lists.
  4. What are some common use cases for dictionaries in Python? Dictionaries are useful for storing configuration data, representing tables of data, implementing caches, and creating efficient lookup structures like hash maps. They also play a crucial role in many algorithms and data structures, such as graphs, trees, and heaps.
  5. How can I create an empty dictionary? You can create an empty dictionary using curly braces {} or the dict() constructor:
empty_dict = {} # Using curly braces
empty_dict2 = dict() # Using dict() constructor
Create a Dictionary (Python Programming) | Python | XQA Learn