Back to Python Notes
Topic #205

Dictionary in Python

By the end of this lesson, you will be able to create, access, and modify Python dictionaries to store and retrieve data efficiently using key-value pairs.

What it is

A dictionary in Python is a built-in data structure that stores data as key-value pairs. Unlike lists, which use integer indices, dictionaries use unique keys (usually strings or numbers) to map directly to values. Think of it like a physical dictionary: you look up a word (the key) to find its definition (the value). This structure allows for extremely fast data retrieval because Python uses hashing internally to locate items without scanning through every element.

Key terms include:

  • key: The unique identifier used to look up a value.
  • value: The data associated with a specific key.
  • hashable: A property required for keys; most immutable types (strings, integers, tuples) are hashable, while mutable types (lists, other dicts) are not.

Why it matters

  • Fast Lookups: Accessing a value by its key takes constant time O(1), regardless of the dictionary size.
  • Structured Data: Ideal for representing objects, configuration settings, or JSON-like data structures.
  • Flexibility: Values can be any data type, including other dictionaries or lists, allowing for nested structures.
  • Readability: Code becomes more self-documenting when using descriptive keys instead of magic numbers or indices.

Syntax or steps

Dictionaries are defined using curly braces {} with colon-separated key-value pairs. Items are separated by commas.

my_dict = {"key1": "value1", "key2": "value2"}

To access a value, use square brackets with the key: my_dict["key1"]. To add or update an item, assign a value to a key: my_dict["new_key"] = "new_value".

Example

The following example creates a student record, accesses data, updates a grade, and adds a new field.

# Create a dictionary
student = {
    "name": "Alice",
    "age": 20,
    "grades": [85, 90, 78]
}

# Access a value
print(student["name"])  # Output: Alice

# Update an existing value
student["age"] = 21

# Add a new key-value pair
student["major"] = "Computer Science"

# Check if a key exists before accessing to avoid errors
if "gpa" in student:
    print(student["gpa"])
else:
    print("GPA not recorded yet.")

print(student)

Explanation: First, we initialize student with three keys. We retrieve "name" directly. Then, we overwrite the "age" value. Next, we insert a completely new key "major". Finally, we use the in operator to safely check for the existence of "gpa" before trying to print it, preventing a KeyError.

Common mistakes

  • Using unhashable keys: You cannot use a list or another dictionary as a key. Use tuples instead if you need composite keys.
  • Assuming order: While modern Python (3.7+) preserves insertion order, do not rely on alphabetical sorting unless explicitly done via sorted().
  • Accessing missing keys: Using dict[key] raises a KeyError if the key doesn't exist. Use dict.get(key) to return None or a default value instead.
  • Mutating during iteration: Do not add or remove keys while looping over the dictionary. Iterate over a copy (list(dict.keys())) if modifications are needed.

When to use it

Compare dictionaries with lists based on how you need to access data.

FeatureListDictionary
Access MethodIndex-based (0, 1, 2...)Key-based ("name", "id"...)
Lookup SpeedO(n) for search by valueO(1) for lookup by key
Best ForOrdered collections of similar itemsMapping relationships or named attributes

Use a list when order matters and you access items by position. Use a dictionary when you need to associate labels with data or perform frequent lookups by name/ID.

Practice

Guided Exercise: Create a dictionary called prices containing three fruits and their costs. Print the price of one fruit, then update the price of another.

Challenge: Write a script that counts the frequency of each letter in the string "hello world" using a dictionary. Hint: Initialize empty dict, loop through characters, check if char is in dict, increment count or set to 1.

Quick check

Question: What happens if you try to access a key that does not exist in a dictionary using square bracket notation?

Answer: It raises a KeyError exception, stopping program execution unless handled with try/except or checked beforehand.

Summary

Python dictionaries provide a powerful way to store data as key-value pairs, enabling fast lookups and structured organization. Mastering methods like get(), keys(), and safe access patterns ensures robust code when managing complex data mappings.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Dictionary in Python – FAQs

Quick answers about learning Dictionary in Python in Python.

This free note from Coding Now Tech Institute explains Dictionary in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Dictionary in Python, is 100% free with no signup required.
With focused practice, most students grasp Dictionary in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now