Dictionaries in Python

    Kedar Kabra3 min readUpdated

    A dictionary stores data as key-value pairs. Instead of looking things up by position (like a list), you look them up by a meaningful key. You write a dictionary with curly braces:

    student = {
        "name": "Asha",
        "age": 21,
        "city": "Jalgaon",
    }
    
    # Look up a value by its key
    print(student["name"])    # Asha
    print(student["age"])     # 21
    

    Think of it like a real dictionary: you look up a word (the key) to find its meaning (the value). Let's dig in.

    Creating and accessing

    Each entry is key: value, separated by commas. Keys are usually strings, and they must be unique:

    prices = {
        "pen": 20,
        "notebook": 60,
        "eraser": 10,
    }
    
    print(prices["notebook"])   # 60
    

    Accessing a missing key with square brackets raises a KeyError. The safer way is .get(), which returns None (or a default you choose) instead of crashing:

    print(prices.get("pencil"))         # None — no crash
    print(prices.get("pencil", 0))      # 0 — your chosen default
    

    Adding and updating

    Assigning to a key adds it if new, or updates it if it already exists:

    student = {"name": "Asha", "age": 21}
    
    student["city"] = "Jalgaon"     # add a new key
    student["age"] = 22             # update an existing key
    
    print(student)
    # {'name': 'Asha', 'age': 22, 'city': 'Jalgaon'}
    

    Removing items

    student = {"name": "Asha", "age": 22, "city": "Jalgaon"}
    
    del student["city"]              # remove a key
    removed = student.pop("age")     # remove and return its value
    print(removed)                   # 22
    print(student)                   # {'name': 'Asha'}
    

    Looping through a dictionary

    You'll often loop over the keys, the values, or both:

    prices = {"pen": 20, "notebook": 60, "eraser": 10}
    

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Loop over keys (the default)

    for item in prices: print(item)

    Loop over keys and values together using .items()

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

    Just the values

    total = 0 for price in prices.values(): total += price print(f"Total: {total}") # 90

    
    ## Checking if a key exists
    
    Use the `in` keyword — it checks keys, not values:
    
    ```python
    prices = {"pen": 20, "notebook": 60}
    
    if "pen" in prices:
        print("We sell pens")
    
    if "stapler" not in prices:
        print("No stapler here")
    

    A practical example

    # Count how many times each word appears in a sentence
    
    sentence = "the cat sat on the mat the cat slept"
    words = sentence.split()       # split into a list of words
    
    counts = {}                    # start with an empty dictionary
    for word in words:
        # If we've seen the word, add 1; otherwise start at 1
        counts[word] = counts.get(word, 0) + 1
    
    print(counts)
    # {'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'slept': 1}
    

    Common mistakes

    • Accessing a missing key with []: d["missing"] raises a KeyError. Use d.get("missing") when a key might not exist.
    • Using a list as a key: Keys must be immutable (strings, numbers, tuples). A list as a key raises a TypeError.
    • Duplicate keys: If you write the same key twice, the last value wins — the earlier one is silently overwritten.
    • Confusing keys and values with in: "pen" in prices checks the keys. To check values, use 20 in prices.values().
    • Forgetting .items() when looping for pairs: for k, v in prices: fails. You need for k, v in prices.items():.

    FAQ

    Are dictionaries ordered? Yes. As of Python 3.7+, dictionaries keep items in the order you inserted them.

    Can values be any type? Yes — values can be numbers, strings, lists, even other dictionaries. Only the keys have the immutability restriction.

    How is a dictionary different from a list? A list uses numeric positions (0, 1, 2...). A dictionary uses meaningful keys you choose. Use a dictionary when each item has a natural label.


    Dictionaries are one of Python's most-used tools. Pair them with Lists in Python and learn about unique collections in Sets in Python. See all topics on the Python learning hub.

    Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Kedar Kabra

    Instructor, Infoplanet

    Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.

    Related guides