PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Python Dictionary Methods: All 11 Methods With Examples

Python Dictionary Methods: All 11 Methods With Examples

Updated on: December 4, 2026 | Leave a Comment

A dictionary stores data as key-value pairs, such as {"name": "Jessa", "age": 28}. Dictionaries have 11 built-in methods for reading values safely, looping over keys and values, adding and updating entries, removing items, and copying.

In this tutorial, you’ll learn every dictionary method with examples, the dictionary merge operators, how view objects behave, and the patterns experienced Python developers use every day.

Key terms used in this article:

  • Key: The unique label used to look up a value. Keys must be hashable (immutable), such as strings, numbers, or tuples.
  • Value: The data stored under a key. Values can be any type.
  • Item: A key-value pair.
  • View object: A live, read-only window into a dictionary’s keys, values, or items. It updates when the dictionary changes.
  • Insertion order: Since Python 3.7, dictionaries remember the order in which keys were added.

Table of contents

  • Dictionary methods at a glance
  • Reading values
    • Square brackets vs. get()
    • Checking whether a key exists
  • Looping with keys(), values(), and items()
    • keys()
    • values()
    • items()
    • View objects are live
  • Adding and updating items
    • Assigning with square brackets
    • update()
    • The merge operators | and |= (Python 3.9+)
    • setdefault()
  • Removing items
    • pop()
    • popitem()
    • del and clear()
  • Copying dictionaries
    • copy()
  • Creating dictionaries with fromkeys()
  • Other useful dictionary operations
  • Related tools: defaultdict and Counter
  • Real-world example: word frequency counter with plain methods
  • Common mistakes
  • Practice exercises
  • Summary

Dictionary methods at a glance

MethodDescription
get(key, default=None)Returns the value for a key, or a default if the key is missing
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of all (key, value) pairs
update(other)Adds or overwrites items from another dictionary or iterable of pairs
setdefault(key, default=None)Returns the value for a key, and inserts the default first if the key is missing
pop(key, default)Removes a key and returns its value
popitem()Removes and returns the last inserted (key, value) pair
clear()Removes all items
copy()Returns a shallow copy
fromkeys(iterable, value=None)Class method that creates a new dictionary from a list of keys

The examples below use this dictionary:

employee = {"name": "Jessa", "role": "Developer", "salary": 7500}
print(employee)
print(len(employee))Code language: Python (python)

Output:

{'name': 'Jessa', 'role': 'Developer', 'salary': 7500}
3

Reading values

Square brackets vs. get()

dict[key] raises a KeyError when the key is missing. get() returns None or a default value instead:

employee = {"name": "Jessa", "role": "Developer", "salary": 7500}

print(employee["name"])
print(employee.get("role"))
print(employee.get("bonus"))         # None
print(employee.get("bonus", 0))      # default value

try:
    print(employee["bonus"])
except KeyError as error:
    print("KeyError:", error)Code language: Python (python)

Output:

Jessa
Developer
None
0
KeyError: 'bonus'

Use square brackets when the key must exist (a missing key is a bug). Use get() when a missing key is normal.

Note that get() doesn’t add the key to the dictionary. Also, if the key exists with the value None, get() returns None, not the default.

Checking whether a key exists

Use in to check keys. It doesn’t search values:

employee = {"name": "Jessa", "role": "Developer", "salary": 7500}

print("salary" in employee)
print("bonus" not in employee)
print("Jessa" in employee)            # False: values aren't checked
print("Jessa" in employee.values())Code language: Python (python)

Output:

True
True
False
True

Looping with keys(), values(), and items()

keys()

employee = {"name": "Jessa", "role": "Developer", "salary": 7500}

print(employee.keys())
for key in employee.keys():
    print(key)Code language: Python (python)

Output:

dict_keys(['name', 'role', 'salary'])
name
role
salary

Looping over the dictionary itself also gives you the keys, so for key in employee: is the usual shortcut.

values()

prices = {"apple": 1.2, "banana": 0.5, "cherry": 3.0}

print(prices.values())
print(sum(prices.values()))
print(max(prices.values()))Code language: Python (python)

Output:

dict_values([1.2, 0.5, 3.0])
4.7
3.0

items()

items() returns (key, value) tuples. Unpack them in the for loop:

prices = {"apple": 1.2, "banana": 0.5, "cherry": 3.0}

for fruit, price in prices.items():
    print(f"{fruit:<8} ${price:.2f}")Code language: Python (python)

Output:

apple    $1.20
banana   $0.50
cherry   $3.00

View objects are live

keys(), values(), and items() return views, not copies. A view always reflects the current contents of the dictionary:

stock = {"pens": 10, "books": 4}
keys = stock.keys()
print(keys)

stock["lamps"] = 2
print(keys)  # the view sees the new key

print(list(keys))  # convert to a list for indexingCode language: Python (python)

Output:

dict_keys(['pens', 'books'])
dict_keys(['pens', 'books', 'lamps'])
['pens', 'books', 'lamps']

Key views behave like sets, so you can compare the keys of two dictionaries directly. The results are sets, which are unordered, so they’re sorted here for a predictable output:

a = {"x": 1, "y": 2, "z": 3}
b = {"y": 20, "z": 30, "w": 40}

print(sorted(a.keys() & b.keys()))   # keys in both
print(sorted(a.keys() - b.keys()))   # keys only in a
print(sorted(a.keys() | b.keys()))   # keys in eitherCode language: Python (python)

Output:

['y', 'z']
['x']
['w', 'x', 'y', 'z']

You can’t add or remove keys while looping over a dictionary. Doing so raises RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.

Adding and updating items

Assigning with square brackets

employee = {"name": "Jessa"}
employee["role"] = "Developer"   # add a new key
employee["name"] = "Jessa Doe"   # update an existing key
print(employee)Code language: Python (python)

Output:

{'name': 'Jessa Doe', 'role': 'Developer'}

update()

update() adds or overwrites several items at once. It accepts another dictionary, an iterable of key-value pairs, or keyword arguments:

employee = {"name": "Jessa", "salary": 7500}

employee.update({"salary": 8000, "city": "London"})
print(employee)

employee.update([("team", "Backend")])
print(employee)

employee.update(level=3, remote=True)
print(employee)Code language: Python (python)

Output:

{'name': 'Jessa', 'salary': 8000, 'city': 'London'}
{'name': 'Jessa', 'salary': 8000, 'city': 'London', 'team': 'Backend'}
{'name': 'Jessa', 'salary': 8000, 'city': 'London', 'team': 'Backend', 'level': 3, 'remote': True}

The merge operators | and |= (Python 3.9+)

| merges two dictionaries into a new one. |= updates a dictionary in place, like update(). When a key exists in both, the value from the right side wins:

defaults = {"theme": "light", "font_size": 12, "autosave": True}
user_prefs = {"theme": "dark", "font_size": 14}

settings = defaults | user_prefs
print(settings)
print(defaults)  # unchanged

defaults |= {"autosave": False}
print(defaults)Code language: Python (python)

Output:

{'theme': 'dark', 'font_size': 14, 'autosave': True}
{'theme': 'light', 'font_size': 12, 'autosave': True}
{'theme': 'light', 'font_size': 12, 'autosave': False}

In older versions, use {**defaults, **user_prefs} to merge into a new dictionary.

setdefault()

setdefault(key, default) returns the value of key if it exists. If it doesn’t, it inserts the key with the default value and returns that value:

config = {"host": "localhost"}

print(config.setdefault("host", "0.0.0.0"))  # exists: unchanged
print(config.setdefault("port", 8080))        # missing: inserted
print(config)Code language: Python (python)

Output:

localhost
8080
{'host': 'localhost', 'port': 8080}

setdefault() is handy for grouping items into lists:

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
    groups.setdefault(word[0], []).append(word)
print(groups)Code language: Python (python)

Output:

{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

For the same job, collections.defaultdict(list) is often cleaner. See the section on related tools below.

Removing items

pop()

pop(key) removes the key and returns its value. Pass a default to avoid a KeyError when the key might be missing:

employee = {"name": "Jessa", "role": "Developer", "salary": 7500}

salary = employee.pop("salary")
print(salary, employee)

print(employee.pop("bonus", "not found"))

try:
    employee.pop("bonus")
except KeyError as error:
    print("KeyError:", error)Code language: Python (python)

Output:

7500 {'name': 'Jessa', 'role': 'Developer'}
not found
KeyError: 'bonus'

popitem()

popitem() removes and returns the last inserted item as a tuple (last in, first out). It raises KeyError on an empty dictionary:

tasks = {"first": 1, "second": 2, "third": 3}

print(tasks.popitem())
print(tasks.popitem())
print(tasks)Code language: Python (python)

Output:

('third', 3)
('second', 2)
{'first': 1}

del and clear()

data = {"a": 1, "b": 2, "c": 3}

del data["a"]
print(data)

data.clear()
print(data)Code language: Python (python)

Output:

{'b': 2, 'c': 3}
{}
You want toUse
Remove a key and get its valuepop(key)
Remove a key that might be missingpop(key, None)
Remove a key without needing the valuedel d[key]
Remove the most recently added itempopitem()
Remove everythingclear()

Copying dictionaries

copy()

b = a doesn’t copy a dictionary. Both names refer to the same object. Use copy() (or dict(a)) for a new dictionary:

original = {"name": "Jessa", "skills": ["Python", "SQL"]}

alias = original
clone = original.copy()

original["name"] = "Kelly"
print(alias["name"], clone["name"])Code language: Python (python)

Output:

Kelly Jessa

copy() is shallow: nested lists and dictionaries are still shared. Use copy.deepcopy() for a fully independent copy:

import copy

original = {"name": "Jessa", "skills": ["Python", "SQL"]}
shallow = original.copy()
deep = copy.deepcopy(original)

original["skills"].append("Docker")
print(shallow["skills"])
print(deep["skills"])Code language: Python (python)

Output:

['Python', 'SQL', 'Docker']
['Python', 'SQL']

Creating dictionaries with fromkeys()

dict.fromkeys(keys, value) creates a new dictionary where every key gets the same value:

fields = ["name", "email", "phone"]

form = dict.fromkeys(fields)
print(form)

counts = dict.fromkeys("aeiou", 0)
print(counts)Code language: Python (python)

Output:

{'name': None, 'email': None, 'phone': None}
{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}

Watch out: If the value is mutable, such as a list, every key shares the same list. Use a dictionary comprehension to give each key its own list: {key: [] for key in fields}.

shared = dict.fromkeys(["a", "b"], [])
shared["a"].append(1)
print(shared)  # both keys changed

separate = {key: [] for key in ["a", "b"]}
separate["a"].append(1)
print(separate)Code language: Python (python)

Output:

{'a': [1], 'b': [1]}
{'a': [1], 'b': []}

dict.fromkeys() is also a quick way to remove duplicates from a list while keeping the order: list(dict.fromkeys(items)).

Other useful dictionary operations

scores = {"Jessa": 88, "Kelly": 95, "Emma": 79}

print(len(scores))
print(sorted(scores))                                  # sorted keys
print(sorted(scores.items(), key=lambda kv: kv[1]))    # sorted by value
print(max(scores, key=scores.get))                     # key with the highest value
print(dict(zip(["x", "y"], [1, 2])))                   # build from two lists
print({v: k for k, v in scores.items()})               # swap keys and values
print(list(reversed(scores)))                          # reverse insertion orderCode language: Python (python)

Output:

3
['Emma', 'Jessa', 'Kelly']
[('Emma', 79), ('Jessa', 88), ('Kelly', 95)]
Kelly
{'x': 1, 'y': 2}
{88: 'Jessa', 95: 'Kelly', 79: 'Emma'}
['Emma', 'Kelly', 'Jessa']

Related tools: defaultdict and Counter

The collections module has two dictionary subclasses that remove a lot of boilerplate.

defaultdict creates a default value automatically when you access a missing key:

from collections import defaultdict

orders = [("Jessa", "pen"), ("Kelly", "book"), ("Jessa", "lamp")]
by_customer = defaultdict(list)
for customer, item in orders:
    by_customer[customer].append(item)
print(dict(by_customer))Code language: Python (python)

Output:

{'Jessa': ['pen', 'lamp'], 'Kelly': ['book']}

Counter counts hashable items:

from collections import Counter

text = "the quick brown fox jumps over the lazy dog the end"
word_counts = Counter(text.split())
print(word_counts.most_common(2))Code language: Python (python)

Output:

[('the', 3), ('quick', 1)]

Real-world example: word frequency counter with plain methods

text = "Python is fun. Python is powerful. Learning Python is fun!"

frequency = {}
for word in text.lower().split():
    word = word.strip(".!,")
    frequency[word] = frequency.get(word, 0) + 1

for word, count in sorted(frequency.items(), key=lambda kv: (-kv[1], kv[0])):
    print(f"{word:<10}{count}")Code language: Python (python)

Output:

is        3
python    3
fun       2
learning  1
powerful  1

frequency.get(word, 0) + 1 is the classic counting pattern: start at 0 if the word is new, otherwise add one to the current count.

Common mistakes

  • Using d[key] for optional keys. Use d.get(key, default) to avoid KeyError.
  • Changing a dictionary while looping over it. Loop over list(d) or build a new dictionary.
  • Expecting in to search values. It checks keys. Use value in d.values().
  • Using mutable keys. Lists can’t be keys (TypeError: unhashable type: 'list'). Use tuples.
  • Sharing a mutable default with fromkeys(). Use a dictionary comprehension instead.
  • Assuming b = a copies the dictionary. Use a.copy() or copy.deepcopy(a).
data = {"a": 1, "b": 2, "c": 3}

# Remove items safely while looping
for key in list(data):
    if data[key] % 2 == 1:
        del data[key]
print(data)

try:
    bad = {["x", "y"]: 1}
except TypeError as error:
    print("Error:", error)

good = {("x", "y"): 1}
print(good)Code language: Python (python)

Output:

{'b': 2}
Error: unhashable type: 'list'
{('x', 'y'): 1}

Practice exercises

Exercise 1: Merge two dictionaries, adding the values of keys that appear in both.

a = {"apples": 3, "pears": 2}
b = {"apples": 5, "plums": 4}

merged = a.copy()
for key, value in b.items():
    merged[key] = merged.get(key, 0) + value
print(merged)Code language: Python (python)

Output:

{'apples': 8, 'pears': 2, 'plums': 4}

Exercise 2: Invert a dictionary of student grades so that each grade maps to a list of students.

grades = {"Jessa": "A", "Kelly": "B", "Emma": "A", "Brad": "C"}
by_grade = {}
for student, grade in grades.items():
    by_grade.setdefault(grade, []).append(student)
print(by_grade)Code language: Python (python)

Output:

{'A': ['Jessa', 'Emma'], 'B': ['Kelly'], 'C': ['Brad']}

Exercise 3: Keep only the items whose value is above a threshold.

prices = {"laptop": 1200, "mouse": 25, "monitor": 300, "cable": 8}
expensive = {item: price for item, price in prices.items() if price > 100}
print(expensive)Code language: Python (python)

Output:

{'laptop': 1200, 'monitor': 300}

Summary

  • Dictionaries have 11 methods: get(), keys(), values(), items(), update(), setdefault(), pop(), popitem(), clear(), copy(), and fromkeys().
  • Use get() to read optional keys safely and in to check whether a key exists.
  • Loop with items() to get keys and values together. keys(), values(), and items() return live views.
  • Add or change items with d[key] = value, update(), or the | and |= operators.
  • Remove items with pop(), popitem(), del, or clear().
  • copy() is shallow. Use copy.deepcopy() for nested data, and avoid mutable defaults with fromkeys().

Also, See:

  • Dictionaries in Python
  • List, Dict, and Set Comprehensions in Python
  • Python Dictionary Exercises
  • Python Dictionary Quiz

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com