PythonCollectionsbeginner

Python Dictionary: Methods and Examples

Python dictionary syntax, methods, safe updates, neat printing and practice problems with answers.

Published
TL;DR – Quick Answer

A Python dictionary stores key and value pairs inside curly braces. You read a value by its key, as in student["name"], or use get when the key may be missing. Keys are unique and must be hashable, and lookups take about the same time at any size on average.

On This Page

A Python dictionary stores data as pairs of keys and values. You look up a value by its key, such as a name or an ID, instead of by its position.

This page covers the syntax, every common method, safe ways to loop and update, ways to print a dictionary neatly, and practice problems with answers.

Python dictionary syntax

The Python dictionary syntax uses curly braces, with a colon between each key and its value.

student = {"name": "Asha", "marks": 82, "city": "Hyderabad"}

print(student["name"])  # Asha
print(len(student))     # 3

There are other ways to make one:

empty = {}
a = dict(name="Ravi", marks=67)
b = dict([("x", 1), ("y", 2)])
c = {n: n * n for n in range(1, 4)}

print(a)  # {'name': 'Ravi', 'marks': 67}
print(b)  # {'x': 1, 'y': 2}
print(c)  # {1: 1, 2: 4, 3: 9}

The last line is a dictionary comprehension. It works like a list comprehension with a key added.

Rules for keys and values

  • Each key is unique. If you repeat a key, the last value wins.
  • A key must be hashable. Strings, numbers and tuples of such values work. Lists and dictionaries do not.
  • A value can be anything, including another dictionary.
  • Since Python 3.7, a dictionary keeps the order in which you add keys.
prices = {"pen": 10, "pen": 20}
print(prices)  # {'pen': 20}

Common mistake: Using {} to make an empty set. {} is an empty dictionary. An empty set is set().

Add, change and remove items

student = {"name": "Asha", "marks": 82}

student["city"] = "Hyderabad"  # new key, so it adds
student["marks"] = 90          # old key, so it changes
print(student)
# {'name': 'Asha', 'marks': 90, 'city': 'Hyderabad'}

removed = student.pop("city")
print(removed)  # Hyderabad

del student["marks"]
print(student)  # {'name': 'Asha'}

pop gives you the removed value. del just removes it. Both raise a KeyError if the key is missing, but pop("city", None) returns None instead.

Read a value safely

student = {"name": "Asha"}

print(student.get("marks"))     # None
print(student.get("marks", 0))  # 0
print("marks" in student)       # False

Using student["marks"] here would stop the program with a KeyError. Use square brackets when the key must be there. Use get when it may be missing.

Python dictionary methods

These are the main Python dictionary methods. In the examples, d = {"a": 1, "b": 2} at the start of each row.

Method What it does Example and result
get(key, default) Reads without an error d.get("z", 0) gives 0
keys() All keys list(d.keys()) gives ['a', 'b']
values() All values list(d.values()) gives [1, 2]
items() All pairs list(d.items()) gives [('a', 1), ('b', 2)]
update(other) Adds or replaces pairs d.update({"b": 9}) makes b 9
pop(key) Removes a key, returns its value d.pop("a") gives 1
popitem() Removes the last pair d.popitem() gives ('b', 2)
setdefault(key, value) Reads, or adds if missing d.setdefault("c", 3) gives 3
copy() Makes a shallow copy d.copy() gives a new dictionary
clear() Removes everything d.clear() leaves {}
dict.fromkeys(keys, value) Builds from a list of keys dict.fromkeys("ab", 0) gives {'a': 0, 'b': 0}

keys(), values() and items() return live views. If the dictionary changes, the view changes too. Wrap one in list() when you need a fixed copy.

Join two dictionaries

base = {"theme": "light", "size": 12}
user = {"theme": "dark"}

print(base | user)        # {'theme': 'dark', 'size': 12}
print({**base, **user})   # {'theme': 'dark', 'size': 12}

The | sign needs Python 3.9 or later. In both forms the right side wins when a key repeats.

Common mistake: Calling dict.fromkeys(["a", "b"], []). Both keys share the same list, so adding to one changes both. Use {k: [] for k in ["a", "b"]}.

Loop through a Python dictionary

marks = {"Asha": 82, "Ravi": 67, "Meena": 91}

for name, score in marks.items():
    print(name, score)
# Asha 82
# Ravi 67
# Meena 91

Looping over the dictionary itself gives you the keys. Use items() when you need both parts.

Sort by key or value

marks = {"Asha": 82, "Ravi": 67, "Meena": 91}

top = sorted(marks.items(), key=lambda pair: pair[1], reverse=True)
print(top)
# [('Meena', 91), ('Asha', 82), ('Ravi', 67)]

print(dict(sorted(marks.items())))
# {'Asha': 82, 'Meena': 91, 'Ravi': 67}

print(max(marks, key=marks.get))
# Meena

Do not change the size while looping

Adding or removing keys inside a loop raises a RuntimeError. Build a new dictionary instead:

marks = {"Asha": 82, "Ravi": 67, "Meena": 91}
high = {k: v for k, v in marks.items() if v > 70}
print(high)  # {'Asha': 82, 'Meena': 91}

Python dictionary examples from real work

These Python dictionary examples show patterns you will use often.

Count things

votes = ["yes", "no", "yes"]
count = {}
for v in votes:
    count[v] = count.get(v, 0) + 1
print(count)  # {'yes': 2, 'no': 1}

collections.Counter(votes) does this in one call. Know both, since many interviewers ask for the manual way.

Group things

words = ["sun", "star", "pen"]
groups = {}
for w in words:
    groups.setdefault(w[0], []).append(w)
print(groups)  # {'s': ['sun', 'star'], 'p': ['pen']}

Nested data

team = {
    "lead": {"name": "Asha", "skills": ["Python", "SQL"]},
    "dev": {"name": "Ravi", "skills": ["React"]},
}

print(team["lead"]["skills"][0])              # Python
print(team.get("tester", {}).get("name"))     # None

The second line reads two levels without an error. Data from a REST API often has this shape.

Replace a long if chain

rates = {"gold": 20, "silver": 10}
print(rates.get("gold", 0))    # 20
print(rates.get("bronze", 0))  # 0

Python dictionary formatter: print it neatly

A long dictionary on one line is hard to read. You do not need an outside Python dictionary formatter, because Python has two built in.

import json

user = {"name": "Asha", "skills": ["Python", "SQL"], "active": True}
print(json.dumps(user, indent=2))

Output:

{
  "name": "Asha",
  "skills": [
    "Python",
    "SQL"
  ],
  "active": true
}

Notice that True became true. The output is JSON text, not Python code. It works only when the values are JSON types, so dates and sets need converting first.

For any Python value, use pprint:

from pprint import pprint
pprint(user, sort_dicts=False)

pprint keeps Python style, such as True and single quotes, and breaks lines only when the data is wide. To tidy JSON text in the browser, paste it into our JSON formatter. It needs valid JSON, so use double quotes.

How a dictionary works inside

A dictionary is a hash table. Python runs hash(key) to get a number and uses that number to find the slot. That is why lookup, insert and delete take about the same time on average, even with a million keys. In big-O terms this is O(1) on average, and O(n) in the rare worst case.

This also explains the rule on keys. If a list could be a key and you changed it later, its hash would change and Python could not find it.

Interview note: "When would you use a dictionary instead of a list?" Answer: when you look things up by a key many times. Searching a list checks items one by one. A dictionary goes to the slot directly.

Two copies need care. d.copy() is shallow, so inner lists are still shared. Use copy.deepcopy(d) when you need a fully separate one.

Python dictionary practice problems

Try these Python dictionary practice problems, then compare your answers.

  1. Count each letter in "banana".
  2. Swap keys and values in {"a": 1, "b": 2}.
  3. Add up marks for repeated names in [("A", 10), ("B", 5), ("A", 7)].
  4. Find the first letter in "swiss" that appears once.
  5. Find two indexes in [2, 7, 11, 15] whose values add to 9.
count = {}
for ch in "banana":
    count[ch] = count.get(ch, 0) + 1
print(count)  # {'b': 1, 'a': 3, 'n': 2}

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

total = {}
for name, mark in [("A", 10), ("B", 5), ("A", 7)]:
    total[name] = total.get(name, 0) + mark
print(total)  # {'A': 17, 'B': 5}

word = "swiss"
freq = {}
for ch in word:
    freq[ch] = freq.get(ch, 0) + 1
print(next(ch for ch in word if freq[ch] == 1))  # w

seen = {}
for i, n in enumerate([2, 7, 11, 15]):
    if 9 - n in seen:
        print(seen[9 - n], i)  # 0 1
        break
    seen[n] = i

Problem 5 is the famous Two Sum. See the same idea with a HashMap in Two Sum in Java. Next, revise the Python basics tutorial and try the Python interview questions. For guided projects, see the Python full stack course.

Frequently Asked Questions

What is a dictionary in Python?
It is a collection of key and value pairs. You use a key, such as a name or ID, to find its value quickly.
What is the difference between get and square brackets?
Square brackets raise a KeyError if the key is missing. get returns None, or a default value that you choose.
Is a Python dictionary ordered?
Yes. Since Python 3.7, the language promises that a dictionary keeps the order in which keys were added.
Can a list be a dictionary key?
No, because a list can change and is not hashable. Use a tuple instead, as long as everything inside the tuple is also hashable.
How do I print a dictionary neatly?
Use json.dumps(d, indent=2) for JSON-style text or pprint.pprint(d) for Python style. json.dumps works only with values that JSON supports, unless you convert them.

Want to Build Your Career in Data Science with AI?

Join CodeBegun and train with working industry engineers — View the Data Science curriculum

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 3 December 2026 LinkedIn
Chat with us