Reading history

Python Dictionaries: Create, Access, Update and Loop

4 min read 2 views

Learn Python dictionaries: creating them, get(), adding and deleting keys, looping with items(), key methods, counting and comprehensions.

A dictionary stores data as key: value pairs, like a phone book that maps names to numbers. Looking up a key is fast no matter how large the dictionary grows, so dictionaries are among Python’s most used types. This lesson shows how to create, read, change and loop over them, plus a word-counting example and dictionary comprehensions.

In this lesson you will learn

  • How to create a dictionary and read values safely
  • How to add, update and delete keys
  • How to loop over keys, values and pairs
  • The most useful dictionary methods
  • How to count things with a dictionary

Creating, Reading and Changing a Dictionary

student = {"name": "Sadia", "age": 21, "dept": "CSE"}

print(student["name"])
print(student.get("cgpa"))           # None instead of an error
print(student.get("cgpa", "not set"))

student["cgpa"] = 3.72               # add a new key
student["age"] = 22                  # update an existing key
del student["dept"]
print(student)
print("age" in student, len(student))

Output

Sadia
None
not set
{'name': 'Sadia', 'age': 22, 'cgpa': 3.72}
True 3
  • student["name"] reads a value, but raises a KeyError if the key is missing.
  • student.get("cgpa") returns None for a missing key, or the default you give as the second argument.
  • Assigning to a new key adds it; assigning to an existing key replaces its value.
  • del removes a key, and in checks whether a key exists.

Rules for keys

Keys must be unique and immutable: strings, numbers and tuples work; lists do not. Values can be anything. Since Python 3.7, dictionaries remember the order in which keys were inserted.

Looping, Methods and Counting

prices = {"rice": 75, "lentils": 120, "oil": 190}

for item, price in prices.items():
    print(f"{item:<8} {price} taka")

print(list(prices.keys()))
print(sum(prices.values()))

prices.update({"oil": 185, "sugar": 140})
removed = prices.pop("lentils")
print("Removed price:", removed)
print(prices)

# count words with a dictionary
words = "to be or not to be".split()
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)

squares = {n: n * n for n in range(1, 5)}
print(squares)

Output

rice     75 taka
lentils  120 taka
oil      190 taka
['rice', 'lentils', 'oil']
385
Removed price: 120
{'rice': 75, 'oil': 185, 'sugar': 140}
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
{1: 1, 2: 4, 3: 9, 4: 16}
  • .items() gives (key, value) pairs; .keys() and .values() give one side each.
  • .update() merges in another dictionary, overwriting matching keys.
  • .pop(key) removes the key and returns its value.
  • Counting pattern: counts[w] = counts.get(w, 0) + 1 starts each new word at 0, then adds 1.
  • Comprehension: {n: n * n for n in range(1, 5)} builds a dictionary in one line.

Dictionary Methods Reference

MethodWhat it does
get(k, default)Value for k, or the default
keys() / values() / items()Views of the keys, values or pairs
update(other)Adds or overwrites keys from other
pop(k)Removes k and returns its value
popitem()Removes and returns the last inserted pair
setdefault(k, v)Returns the value of k, inserting v first if k is missing
clear() / copy()Empty the dictionary / make a shallow copy

Common Mistakes

  1. Reading a missing key with []. Use get() or check with in first.
  2. Changing the size while looping. Adding or deleting keys inside for k in d: raises an error. Loop over list(d) instead.
  3. Using a list as a key. Convert it to a tuple.
  4. Expecting {} to be a set. {} is an empty dictionary.

Practice Exercises

Exercise 1. Find the student with the highest mark in {"Rafi": 81, "Nila": 92, "Tanim": 77}.

Show answer
marks = {"Rafi": 81, "Nila": 92, "Tanim": 77}
print(max(marks, key=marks.get))   # Nila

Exercise 2. Swap the keys and values of {"a": 1, "b": 2}.

Show answer
d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()})   # {1: 'a', 2: 'b'}

Frequently Asked Questions

Are Python dictionaries ordered?

Yes, since Python 3.7 they keep insertion order. They still cannot be sorted in place; use sorted(d.items()) to get a sorted list of pairs.

How do I merge two dictionaries?

Use a | b (Python 3.9+) for a new dictionary, or a.update(b) to change a. On duplicate keys, the value from b wins.

Why are dictionary lookups fast?

Dictionaries are hash tables: Python hashes the key to find its slot directly instead of searching. The idea is explained in Hashing in Data Structures.

Summary

  • Dictionaries map unique, immutable keys to values.
  • Use get() for safe reads and in to test for a key.
  • Loop with .items() to get key and value together.
  • counts.get(k, 0) + 1 is the standard counting pattern.

Next: Python Tuples.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *