Python • Collections and Strings

Dictionary Creation & Access — Create dictionaries and access/update values by key

Learn how Python dictionaries let you store and retrieve data instantly using meaningful keys instead of numeric positions.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Imagine you have a contact list on your phone. You don't look up a friend by saying "give me person number 47"—you search by their name and instantly get their phone number. This idea of pairing a lookup key with a stored value is one of the most powerful concepts in all of computer science. Long before Python existed, programmers needed a way to organize data so they could find it quickly without scanning through every item one by one.

Lists and arrays store items in numbered positions, which works great when you know the index. But what if you want to store a student's grade by their name, or look up the capital of a country? You need a data structure that maps one piece of information to another. This need gave rise to the hash map (also called a hash table), which Python implements as the dictionary.

1953 • Hash Tables Invented

Hans Peter Luhn at IBM developed the concept of a hash table, a data structure that uses a mathematical function to map keys to storage locations for near-instant lookups.

1991 • Python 0.9 Released

Guido van Rossum released the first version of Python, which already included built-in dictionaries as a core data type—signaling how fundamental key-value storage is to the language.

2000 • Python 2.0 — Dictionary Methods Expand

Python 2.0 added powerful dictionary methods like .get() and .update(), making dictionaries even more flexible and developer-friendly.

2017 • Python 3.7 — Insertion Order Guaranteed

Starting with Python 3.7, dictionaries officially preserve the order in which keys are inserted. Earlier versions did not guarantee any particular order.

The core question this lesson addresses is straightforward: How do you create a dictionary in Python, and how do you access or change the values stored inside it? Understanding dictionaries unlocks the ability to model real-world relationships in your code—from student grades to game inventories to website data.

SECTION 2

Core Principles & Definitions

A dictionary in Python (abbreviated dict) is an unordered collection of key-value pairs. Each key acts as a unique label that maps to exactly one value. You can think of it like a real-world dictionary: the word (key) maps to its definition (value). There are a few essential principles you need to know before writing your first dictionary.

1

Key-Value Pairs

Every entry in a dictionary consists of a key paired with a value. The key is what you use to look things up; the value is what you get back. Written as key: value.
2

Keys Must Be Unique

No two entries can share the same key. If you assign a new value to an existing key, it overwrites the old value. Think of it like a phone contact—one name can only store one phone number at a time.
3

Keys Must Be Immutable

Keys must be immutable (unchangeable) types like strings, integers, or tuples. Lists cannot be keys because they can change after creation, which would break the internal lookup system.
4

Values Can Be Anything

While keys are restricted, values have no such limitation. A value can be a string, integer, list, another dictionary, or any Python object. This makes dictionaries incredibly flexible.
5

Fast Lookups — O(1)

Dictionaries use a hash function behind the scenes. This means looking up a value by its key takes roughly the same amount of time whether the dictionary has 10 items or 10 million.
✦

KEY TAKEAWAY

Think of a Python dictionary like a locker system at school. Each locker has a unique number (the key), and inside it you can store whatever you want (the value). You don't need to check every locker to find your stuff—you just go straight to your locker number. That's the power of key-based access: you jump directly to what you need.

SECTION 3

Visual Explanation — Dictionary Structure

The diagram below shows how a Python dictionary organizes key-value pairs internally. On the left, you can see the keys—unique labels that point to their corresponding values on the right. The curly braces { } surround the whole structure, and each pair is separated by a comma.

Python Dictionary: student_infostudent_info = {"name": "Alice", "grade": 11, "gpa": 3.8, "clubs": ["Chess", "Code"]}KEYSVALUES"name""Alice""grade"11"gpa"3.8"clubs"["Chess", "Code"]Each key is unique and immutable · Values can be any Python type
The violet boxes on the left represent keys (all strings in this example), and the cyan boxes on the right represent their corresponding values (a string, an integer, a float, and a list). Arrows show the one-to-one mapping between each key and its value.

Notice that the values are diverse: "Alice" is a string, 11 is an integer, 3.8 is a float, and ["Chess", "Code"] is a list. This flexibility is a major advantage of dictionaries—unlike a list where every element is accessed by a numeric index, here you access data with a meaningful, human-readable key.

SECTION 4

How It Works — Creating Dictionaries

Python gives you several ways to create a dictionary. The most common approach uses curly brace literal syntax, but you can also use the built-in dict() constructor or start with an empty dictionary and add items one at a time. Let's look at each method and understand when to use it.

Method 1 — Curly Brace Literals

LITERAL SYNTAX

mydict=key1:value1,key2:value2,key3:value3my_dict = { key₁: value₁, key₂: value₂, key₃: value₃ }

Each key: value pair is separated by commas. Keys and values are separated by a colon. The entire collection is wrapped in curly braces { }.

For example, scores = {"math": 92, "english": 88, "science": 95} creates a dictionary with three subjects as keys and their scores as values. This is the most common and readable way to create a dictionary when you already know the data.

Method 2 — The dict() Constructor

CONSTRUCTOR SYNTAX

mydict=dict(key1=value1,key2=value2)my_dict = dict(key₁=value₁, key₂=value₂)

When using dict(), keys are passed as keyword arguments (no quotes around them) and they must be valid Python identifiers. This only works when keys are simple strings.

Method 3 — Start Empty, Add Later

EMPTY DICT + ASSIGNMENT

mydict=→mydict[key]=valuemy_dict = { } → my_dict[key] = value

Create an empty dictionary first with {} or dict(), then add entries one at a time using bracket notation. This is useful when building a dictionary dynamically inside a loop.

⚠

Common Pitfall

Be careful: {} creates an empty dictionary, not an empty set. To create an empty set, you must use set(). This is one of the most common mistakes beginners make in Python.

SECTION 5

Accessing & Updating Values

Once you've created a dictionary, you need to know how to read values, update existing entries, and add new pairs. Python provides two primary ways to access values: bracket notation and the .get() method. Understanding the difference between them is essential.

Accessing & Updating Dictionary Values1 · BRACKET NOTATION — READscores = {"math": 92, "english": 88, "science": 95}print(scores["math"]) # Output: 922 · .get() METHOD — SAFE READprint(scores.get("math")) # Output: 92print(scores.get("art")) # Output: None (no error!)print(scores.get("art", 0)) # Output: 0 (custom default)3 · UPDATE AN EXISTING VALUEscores["math"] = 97 # Updates math from 92 → 97print(scores) # {"math": 97, "english": 88, "science": 95}4 · ADD A NEW KEY-VALUE PAIRscores["art"] = 90 # Adds a brand-new entryprint(scores) # {"math": 97, "english": 88, "science": 95, "art": 90}Bracket notation for new keys = add · For existing keys = update · .get() prevents KeyError crashes
This diagram shows four fundamental operations: reading with [ ], safe reading with .get(), updating existing values, and adding new key-value pairs. Notice that adding and updating use the same syntax—Python decides based on whether the key already exists.
OperationSyntaxBehavior if Key Missing
Read (bracket)d[key]Raises KeyError
Read (safe)d.get(key, default)Returns None or your chosen default
Update existingd[key] = new_valueCreates a new entry instead
Add newd[new_key] = valueAlways creates the entry
Deletedel d[key]Raises KeyError

Common dictionary operations and their behavior

SECTION 6

Worked Example — Building a Student Gradebook

Let's walk through a realistic scenario. You're building a simple gradebook program that stores a student's name and their scores in different subjects. We'll create the dictionary, access values, update a grade after a retest, and add a new subject.

Building and Modifying a Gradebook Dictionary

  1. 1

    Step 1 — Create the dictionary

    Start by defining the gradebook with known subjects and scores. We use string keys for subject names and integer values for grades. gradebook = {"algebra": 85, "biology": 91, "history": 78}
    Dictionary created with 3 key-value pairs.
  2. 2

    Step 2 — Access a specific grade

    To check the biology grade, use bracket notation with the key "biology". bio_grade = gradebook["biology"] print(bio_grade)
    Output: 91
  3. 3

    Step 3 — Safely check for a grade that might not exist

    What if we want the chemistry grade but we're not sure it's been entered? Using .get() prevents a crash. chem_grade = gradebook.get("chemistry", "Not enrolled") print(chem_grade)
    Output: Not enrolled — No error, just the default value.
  4. 4

    Step 4 — Update a grade after a retest

    The student retook the history exam and scored 88. We update by assigning a new value to the existing key. gradebook["history"] = 88 print(gradebook)
    Output: {"algebra": 85, "biology": 91, "history": 88}
  5. 5

    Step 5 — Add a new subject

    The student just started an art class. We add a new key that doesn't exist yet. gradebook["art"] = 94 print(gradebook)
    Final output: {"algebra": 85, "biology": 91, "history": 88, "art": 94}
💡

Pro Tip

Use the in keyword to check if a key exists before using bracket notation: if "chemistry" in gradebook:. This is another way to avoid a KeyError without using .get().

SECTION 7

Dictionaries vs. Lists — When to Use Which

If you already know Python lists, you might wonder when to use a dictionary instead. Both store collections of data, but they're designed for very different purposes. The table below compares the two data structures across several key dimensions.

FeatureListDictionary
Access MethodBy numeric index: my_list[0]By key: my_dict["name"]
OrderOrdered by positionOrdered by insertion (Python 3.7+)
Lookup SpeedO(n) — must scan through items to find a valueO(1) — jumps directly to the value via its key
DuplicatesAllows duplicate valuesKeys must be unique; values can repeat
Best ForOrdered sequences of similar items (e.g., a list of temperatures)Named data fields or lookups (e.g., student records, settings)

List vs. Dictionary comparison

✦

KEY TAKEAWAY

Use a list when you care about the position of items (like a playlist in order). Use a dictionary when you care about the label of items (like a contacts app where you search by name). If you find yourself thinking "I need to look something up by a name or identifier," a dictionary is almost always the right choice.

SECTION 8

Connection to Advanced Topics

The basics of dictionary creation and access are the foundation for many powerful Python techniques. As you progress, you'll encounter more advanced ways to work with dictionaries. The table below previews some of these topics and how they build on what you've learned today.

What You Learned TodayWhat Comes Next
Creating dictionaries with { }Dictionary comprehensions: Build dicts in one line with {k: v for k, v in iterable}
Accessing with d[key] and .get()Iterating with loops: Use .keys(), .values(), and .items() to loop through dictionaries
Single-level key-value pairsNested dictionaries: Dictionaries inside dictionaries for complex data like JSON
Manual default handling with .get()defaultdict from the collections module: Automatically provides default values for missing keys

From basics to advanced dictionary techniques

Dictionaries are also the engine behind many real-world applications. Web APIs send data as JSON (JavaScript Object Notation), which maps almost directly to Python dictionaries. When you build web apps, games, or data science projects, you'll be working with dictionaries constantly. Mastering creation and access now sets you up for everything that follows.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why a Python dictionary requires its keys to be immutable types (like strings or integers) but allows values to be any type, including lists. What would go wrong if a list could be used as a key?
Show answer
Python uses a hash function to convert each key into a fixed numeric address where the value is stored. Immutable types always produce the same hash, so Python can reliably find the value later. If a list were used as a key and then modified (say, an item was appended), its hash would change, and Python would no longer be able to locate the original entry. The value would effectively be lost in memory. Values don't need to be immutable because they're just stored at the address—they aren't used for lookups.

Question 2: BASIC CALCULATION

Given the following dictionary, what does each print statement output? inventory = {"apples": 5, "bananas": 12, "oranges": 8} a) print(inventory["bananas"]) b) print(inventory.get("grapes", 0)) c) print(inventory.get("apples", 0))
Show answer
a) 12 — The key "bananas" exists, so bracket notation returns its value directly. b) 0 — The key "grapes" does not exist in the dictionary, so .get() returns the default value of 0 instead of crashing. c) 5 — Even though a default of 0 is provided, the key "apples" does exist, so .get() returns the actual stored value of 5. The default is only used when the key is missing.

Question 3: INTERMEDIATE

Write Python code that starts with an empty dictionary called word_counts and then processes the list words = ["hello", "world", "hello", "python", "world", "hello"]. After processing, word_counts should contain each unique word as a key and the number of times it appears as the value.
Show answer
Here is one solution: word_counts = {} words = ["hello", "world", "hello", "python", "world", "hello"] for word in words: word_counts[word] = word_counts.get(word, 0) + 1 The result is {"hello": 3, "world": 2, "python": 1}. The trick is using .get(word, 0) to safely return 0 for the first occurrence of any word, then adding 1 each time the word appears again. This is one of the most common patterns in Python programming.

Question 4: APPLIED

You are building a simple contact book app. Write a Python program that: (1) creates a dictionary with at least 3 contacts where the key is the person's name and the value is their phone number, (2) prints a specific contact's number, (3) updates one contact's number, and (4) adds a new contact. Show the final dictionary.
Show answer
contacts = {"Alice": "555-1234", "Bob": "555-5678", "Carol": "555-9012"} print(contacts["Bob"]) # 555-5678 contacts["Alice"] = "555-0000" # Update Alice's number contacts["Diana"] = "555-3456" # Add new contact print(contacts) The final output is {"Alice": "555-0000", "Bob": "555-5678", "Carol": "555-9012", "Diana": "555-3456"}. Notice that Alice's number changed from "555-1234" to "555-0000" (update), and Diana was added as a completely new entry. Both operations use the same bracket-assignment syntax—Python automatically knows whether to create or update based on whether the key exists.

Question 5: CRITICAL THINKING

Consider the following code: settings = {"volume": 80, "brightness": 70} backup = settings settings["volume"] = 50 print(backup["volume"]) What does this print, and why? What would you do differently if you wanted backup to remain unchanged?
Show answer
This prints 50, not 80. The line backup = settings does not create a copy of the dictionary—it creates a second reference (or alias) pointing to the exact same dictionary object in memory. When you modify settings["volume"], you're modifying the same object that backup also points to. To create an independent copy, you should use backup = settings.copy() or backup = dict(settings). This is a critical concept called aliasing vs. copying, and it applies to lists and other mutable objects in Python as well.

SUMMARY

Dictionary Creation & Access — Summary

Summary

A Python dictionary stores data as key-value pairs inside curly braces { }. Keys must be unique and immutable (strings, integers, or tuples), while values can be any Python type. You can create dictionaries using literal syntax, the dict() constructor, or by starting empty and adding items one at a time.

To read a value, use bracket notation d[key] for direct access (raises KeyError if missing) or the .get() method for safe access with a default fallback. To update an existing value or add a new entry, use the same d[key] = value syntax—Python creates the key if it's new or overwrites it if it exists. Dictionaries provide O(1) constant-time lookups, making them one of the most efficient and widely-used data structures in Python.

Varsity Tutors • Python • Dictionary Creation & Access