Vinay Garg Assistant Professor

Lesson 19: Dictionaries: values stored under keys

A dictionary stores values under named keys instead of numbered positions. That makes it the right structure for records — a student, a product, a config file — where you look things up by name.

A dark code window showing a dictionary of student details and its items

In short

  • A dictionary holds key: value pairs and is written with curly brackets.
  • You read a value by key: `student["name"]`; `get()` returns a default instead of raising an error.
  • Keys must be unique and hashable; the insertion order of keys is preserved.
  • `keys()`, `values()` and `items()` give you the three views you need for looping.

3

views for looping: keys(), values(), items()

Python docs

1

default returned by get() when the key is missing: None

Python docs

What a dictionary is

A dictionary is a collection of key–value pairs. Instead of reaching an item by its position, you reach it by its key. The key is usually a string, and the value can be anything, including a list or another dictionary.

student = {"name": "Asha", "roll": 21, "course": "MCA"}
print(student["name"])     # Asha

The program

# dicts.py — reading, adding, updating and looping

student = {"name": "Asha", "roll": 21, "course": "MCA"}

print(student["name"])                        # Asha
print(student.get("marks", "not set"))        # not set, no error

student["marks"] = 88                         # new key
student["course"] = "MCA (Computer Science)"  # update
print(student)

for key, value in student.items():
    print(key, "=", value)

print("name" in student, len(student))        # True 4
print(student.keys())

del student["roll"]
print(student)

How it works, step by step

  1. student["name"] looks up the key and returns its value. If the key is absent, this form raises KeyError.
  2. get("marks", "not set") returns the default instead of failing, which is the safe way to read optional keys.
  3. Assigning to a new key adds it; assigning to an existing key replaces the value.
  4. items() gives pairs, which is why the loop has two names.
  5. in tests keys, and len() counts pairs.
  6. del removes a key and its value together.

What it prints

Asha
not set
{'name': 'Asha', 'roll': 21, 'course': 'MCA (Computer Science)', 'marks': 88}
name = Asha
roll = 21
course = MCA (Computer Science)
marks = 88
True 4
dict_keys(['name', 'roll', 'course', 'marks'])
{'name': 'Asha', 'course': 'MCA (Computer Science)', 'marks': 88}

The methods you need

CallResult
d[key]The value, or KeyError
d.get(key, default)The value, or the default
d[key] = valueAdd or update
del d[key], d.pop(key)Remove
d.keys(), d.values(), d.items()Views for looping
key in dTrue when the key exists
d.update(other)Merge another dictionary in

Nested dictionaries

college = {
    "name": "MMM College",
    "students": {
        "asha": {"roll": 21, "marks": 88},
        "ravi": {"roll": 22, "marks": 74},
    },
}
print(college["students"]["asha"]["marks"])   # 88

Common mistakes

  • Using d["missing"] when the key may not exist. Use get().
  • Assuming the order is alphabetical. It is insertion order, which is only the same thing by accident.
  • Using a list as a key. Keys must be hashable, so use a tuple instead.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Build a dictionary for a book with title, author and price, then print each value by key.
  2. Add a new key for the year, change the price, and print the dictionary.
  3. Loop through the dictionary and print every key with its value.
  4. Count how many times each word appears in a sentence using a dictionary.

Sources

Frequently asked questions

What is a dictionary in Python?

A collection of key-value pairs. You store a value under a name and read it back by that name instead of by position, which suits records such as a student or a product.

What is the difference between [] and get() on a dictionary?

square brackets raise KeyError when the key is missing. get() returns None, or a default you choose, which is safer for optional data.

Can a dictionary have duplicate keys?

No. Assigning to an existing key replaces its value, so each key appears once. The pairs keep the order in which they were first inserted.

Are dictionaries ordered in Python?

Yes, from Python 3.7 onwards insertion order is guaranteed. That does not mean sorted: sorted(d) gives the keys in alphabetical order when you need that.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.