100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

Dictionaries in Python

Python's key-value mapping type, covering hashable keys, insertion order guarantees (3.7+), common dict methods, and typical gotchas.

Data StructuresBeginner12 min readJul 7, 2026
Analogies

1. Introduction

A dictionary (dict) is Python's built-in mapping type that stores data as key-value pairs. Each key must be unique and hashable, and it maps to an associated value, allowing very fast lookups, insertions, and deletions by key.

🏏

Cricket analogy: A scorer's player-to-runs mapping is a dict—each player name (key) must be unique and maps to their score (value), enabling instant lookup of "how many runs did Kohli score" without scanning the whole innings.

Dictionaries are defined with curly braces {} containing key: value pairs separated by commas. They are widely used for representing structured data, counting occurrences, caching, and configuration settings.

🏏

Cricket analogy: A dict like {"Kohli": 82, "Rohit": 45} defined with curly braces is how a scorer tallies runs per batsman, and the same structure works for counting boundaries or caching last innings' totals for quick reference.

2. Syntax

python
# Creating dictionaries
empty_dict = {}
person = {"name": "Alice", "age": 30}

# Accessing and modifying values
name = person["name"]
person["age"] = 31
person["city"] = "NYC"       # adds a new key

# Safe access
city = person.get("country", "Unknown")

# Common methods
keys = person.keys()
values = person.values()
items = person.items()
person.pop("city")

# Iterating
for k, v in person.items():
    pass

3. Explanation

Dictionary keys must be hashable — meaning immutable types like strings, numbers, and tuples (of hashable items) can be keys, but mutable types like lists and other dicts cannot. Values, on the other hand, can be of any type, including other dictionaries or lists.

🏏

Cricket analogy: A scorecard can't use a lineup (a mutable list of batsmen) as a dictionary key because it might change mid-match, but it can happily use a player's fixed jersey number as the key mapping to a nested dict of full stats as the value.

Since Python 3.7, dictionaries officially guarantee that they preserve insertion order — iterating over a dict yields keys in the order they were added, which is useful for predictable output and ordered processing.

🏏

Cricket analogy: Since a scorecard now guarantees deliveries are listed in the order they were bowled, a commentator can iterate ball-by-ball exactly as it happened, just as dicts since Python 3.7 preserve insertion order.

Using a mutable object like a list as a dictionary key raises TypeError: unhashable type: 'list'. If you need a composite key, use a tuple instead, e.g. cache[(x, y)] = result.

Accessing a missing key with person['country'] raises a KeyError. Prefer person.get('country', default) or if key in person: to avoid exceptions when a key might not exist.

4. Example

python
person = {}
person["name"] = "Alice"
person["age"] = 30
person["city"] = "NYC"

for key, value in person.items():
    print(key, "->", value)

print("get missing:", person.get("country", "Unknown"))

try:
    print(person["country"])
except KeyError as e:
    print("KeyError:", e)

try:
    bad = {[1, 2]: "value"}
except TypeError as e:
    print("TypeError:", e)

5. Output

text
name -> Alice
age -> 30
city -> NYC
get missing: Unknown
KeyError: 'country'
TypeError: unhashable type: 'list'

6. Key Takeaways

  • Dictionaries store unique, hashable keys mapped to values of any type.
  • Since Python 3.7, dicts preserve insertion order when iterated.
  • Accessing a missing key with [] raises KeyError; use .get() for a safe default.
  • Lists and other dicts cannot be used as keys because they are unhashable; use tuples instead.
  • .keys(), .values(), and .items() return view objects that reflect live changes to the dict.
  • dict.pop(key) removes a key and returns its value, similar to list.pop() for lists.

Practice what you learned

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#DictionariesInPython#Dictionaries#Syntax#Explanation#Example#DataStructures#StudyNotes#SkillVeris