agyanadda@gmail.com

Python Dictionaries

Python Data Structures 1 min read Updated Dec 4, 2026 Topic 15 of 32

A dictionary (dict) stores key: value pairs. It is ordered (by insertion), changeable, and keys must be unique.

student = {"name": "Asha", "age": 21, "course": "BCA"}

Access

  • student["name"] — KeyError if missing
  • student.get("phone") → None; get("phone", "N/A") with a default
  • "age" in student — check a key

Add, change, delete

  • student["city"] = "Patna" — add or update
  • update({...}) — several at once
  • pop("age"), del student["age"], popitem(), clear()
  • setdefault(key, default)

Loop

  • for key in d:
  • for value in d.values():
  • for key, value in d.items():

Nested dictionaries

Values can be lists or other dicts — this is how JSON data looks in Python.

Helpers

  • dict.fromkeys(keys, 0)
  • merged = a | b (Python 3.9+)
  • collections.Counter — count items
  • collections.defaultdict — automatic default values

Keys must be immutable: strings, numbers or tuples.

Example

Example — Student records Python
from collections import Counter

student = {"name": "Asha", "age": 21, "marks": {"math": 88, "physics": 76}}

print(student["name"], student.get("phone", "N/A"))
student["city"] = "Patna"
student["marks"]["chemistry"] = 91

for subject, mark in student["marks"].items():
    print(f"{subject:<10}{mark}")

total = sum(student["marks"].values())
print("Total:", total)

words = "to be or not to be".split()
print(Counter(words).most_common(2))

defaults = {"theme": "light", "lang": "en"}
user = {"lang": "hi"}
print(defaults | user)

Prints Asha N/A, a table of subjects and marks including chemistry 91, Total: 255, [('to', 2), ('be', 2)], and {'theme': 'light', 'lang': 'hi'} — the user's value wins when merging.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns None instead of an error for a missing key?

Exercise 2 True / False

Dictionary keys must be unique.

Exercise 3 Fill in the Blank

Loop over keys and values together with d.___()

Frequently Asked Questions

Yes. Since Python 3.7, dictionaries keep the order in which keys were inserted.