Python Dictionaries Explained for Beginners

Dictionaries store data as key-value pairs, letting you look up a value instantly by a meaningful name instead of a numeric position. This guide covers creating, accessing, and modifying dictionaries — the final data structure in this Python for Beginners series.

If you’ve worked through our guides on lists and tuples, dictionaries are the natural next structure: instead of a numeric index, each value has a named key.

What a Dictionary Actually Is

According to freeCodeCamp’s guide to Python dictionaries, a dictionary organizes data as key-value pairs wrapped in curly braces, with each key mapped to exactly one value:

student = {
    "name": "Alex",
    "age": 21,
    "major": "Computer Science"
}

Accessing Values by Key

print(student["name"])  # Alex
print(student["age"])   # 21

Unlike a list, where you access items by numeric position, a dictionary looks up values by their key directly — genuinely faster to reason about once your data has meaningful names rather than arbitrary positions.

Adding and Updating Values

According to CodeSolid’s dictionary lesson for beginners, dictionaries don’t have an append() method the way lists do — instead, you add or update a value using the same bracket syntax as an assignment:

student["email"] = "alex@example.com"  # adds a new key
student["age"] = 22                     # updates an existing key

Checking If a Key Exists

Trying to access a missing key with brackets raises a KeyError. The safer approach uses .get(), which returns None (or a default you specify) instead of crashing:

print(student.get("phone"))          # None
print(student.get("phone", "N/A"))   # N/A

Looping Through a Dictionary

for key, value in student.items():
    print(f"{key}: {value}")

.items() gives you both the key and value together in each iteration — the most common looping pattern. .keys() and .values() are available separately when you only need one side.

Removing a Key

del student["email"]
# or
student.pop("email")

pop() also returns the removed value, which is useful if you need to do something with it afterward; del simply removes it.

Dictionaries vs. Lists: When to Use Each

Use a list when order and position matter and items don’t need individual names. Use a dictionary when each piece of data has a natural, meaningful label — a person’s attributes, a configuration setting, or anything you’d otherwise describe with “the X of Y.” According to a beginner-focused Python dictionaries tutorial, dictionaries don’t guarantee any particular ordering the way a list does, so if you specifically need an ordered sequence, a list remains the better fit.

Dictionary Comprehensions

Similar to list comprehensions, Python supports a compact syntax for building a dictionary from an iterable in one line:

squares = {n: n**2 for n in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This creates a dictionary mapping each number to its square, combining the loop and the key-value creation into a single expression — a shorter alternative to writing out a full for loop with individual assignments, once the basic dictionary syntax feels comfortable.

Checking Dictionary Length

print(len(student))  # number of key-value pairs

len() works on dictionaries the same way it does on lists and strings, returning the count of key-value pairs currently stored.

A Practical Example: Counting Word Frequency

Dictionaries are genuinely well suited to counting and grouping tasks. Here’s a small example counting how often each word appears in a list:

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)  # {'apple': 3, 'banana': 2, 'cherry': 1}

This combines a for loop with .get()‘s default value to build up counts incrementally — starting each new word at 0 and incrementing it every time it’s seen again, a genuinely common real-world use case for dictionaries.

Nested Dictionaries

According to a comprehensive Python dictionaries tutorial from Scholarhat, dictionary values are mutable and can hold any data type, including other dictionaries — enabling genuinely structured, multi-level data:

students = {
    "alex": {"age": 21, "major": "CS"},
    "sam": {"age": 23, "major": "Math"}
}

print(students["alex"]["major"])  # CS

This pattern — a dictionary of dictionaries — is common once you’re representing collections of records, each with its own set of named attributes, rather than a single flat set of key-value pairs.

Common Questions

Can dictionary keys be anything? Keys must be immutable — strings, numbers, or tuples work; lists cannot be used as keys, since lists are mutable.

Can I nest a dictionary inside another dictionary? Yes, and it’s a genuinely common pattern for representing more complex, structured data — a dictionary of students, where each value is itself a dictionary of that student’s details.

Quick-Reference Guide

  • {key: value} — the basic dictionary syntax.
  • dict[key] — access a value; raises KeyError if missing.
  • dict.get(key, default) — safer access with a fallback.
  • dict[key] = value — add or update a key.
  • .items() / .keys() / .values() — different ways to loop through a dictionary.
  • del / .pop() — remove a key.

Conclusion

Dictionaries round out the core Python data structures covered in this series — variables, lists, tuples, and now key-value pairs — giving you the right tool for nearly any shape of data you’ll encounter as a beginner. This completes the Python for Beginners series covered throughout this blog.

Explore More Python for Beginners Guides →

Leave a Comment

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

Scroll to Top