Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary: Methods

Python Dictionary Methods - Complete Guide

Learn how to use Python dictionary methods including keys, values, items, get, update, pop, and more.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Dictionary Methods
  • keys() — Get All Keys
  • values() — Get All Values
  • items() — Get Key-Value Pairs
  • get() — Safe Value Retrieval
  • update() — Merge Dictionaries
  • pop() — Remove and Return
  • popitem() — Remove Last Item
  • clear() — Remove All
  • copy() — Create a Copy
  • fromkeys() — Create from Keys
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • keys() — get all keys in a dictionary
  • values() — get all values in a dictionary
  • items() — get all key-value pairs
  • get() — safely retrieve values
  • update() — merge dictionaries
  • pop() — remove and return values
  • popitem() — remove last item
  • clear() — remove all items
  • copy() — create a copy
  • fromkeys() — create from keys

Introduction to Dictionary Methods

Python dictionaries provide a rich set of built-in methods for performing various operations. These methods can be categorized into several groups:

  • View methods: keys(), values(), items()
  • Access methods: get(), setdefault()
  • Modification methods: update(), pop(), popitem(), clear()
  • Utility methods: copy(), fromkeys()

Most dictionary methods modify the dictionary in place, meaning they change the original dictionary rather than creating a new one.

💡 Key concept: Dictionary view objects (keys(), values(), items()) provide a dynamic view of the dictionary. Changes to the dictionary are reflected in the view.

keys() — Get All Keys

1

Accessing All Keys

The keys() method returns a view object containing all the keys in the dictionary. This view is dynamic and reflects changes to the dictionary.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
keys = person.keys()
print(keys)  # dict_keys(['name', 'age', 'city'])

# Converting to a list
keys_list = list(person.keys())
print(keys_list)  # ['name', 'age', 'city']

# Iterating over keys
for key in person.keys():
    print(f"Key: {key}")

# Dynamic view (reflects changes)
person["email"] = "alice@example.com"
print(keys)  # dict_keys(['name', 'age', 'city', 'email'])

# Checking if a key exists
if "name" in person.keys():
    print("Name key exists")

# Using with set operations
keys_set = set(person.keys())
print(keys_set)  # {'name', 'age', 'city', 'email'}

Characteristics:

  • Returns a view object (dynamic)
  • Reflects changes to the dictionary
  • Can be converted to a list or set
  • Time complexity: O(1) to get the view, O(n) to iterate

Quick Check: What type of object does keys() return? (Answer: A view object)

values() — Get All Values

2

Accessing All Values

The values() method returns a view object containing all the values in the dictionary. This view is dynamic and reflects changes to the dictionary.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
values = person.values()
print(values)  # dict_values(['Alice', 25, 'NYC'])

# Converting to a list
values_list = list(person.values())
print(values_list)  # ['Alice', 25, 'NYC']

# Iterating over values
for value in person.values():
    print(f"Value: {value}")

# Dynamic view
person["email"] = "alice@example.com"
print(values)  # dict_values(['Alice', 25, 'NYC', 'alice@example.com'])

# Checking if a value exists
if "Alice" in person.values():
    print("Alice is in the dictionary")

# Using with set operations (values may not be hashable)
values_set = set(person.values())  # Works if all values are hashable

Characteristics:

  • Returns a view object (dynamic)
  • Reflects changes to the dictionary
  • May contain duplicate values
  • Can be converted to a list or set

Quick Check: Can values() contain duplicate values? (Answer: Yes, because values are not required to be unique)

items() — Get Key-Value Pairs

3

Accessing All Key-Value Pairs

The items() method returns a view object containing all key-value pairs as tuples. This is the most commonly used method for iterating over dictionaries.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
items = person.items()
print(items)  # dict_items([('name', 'Alice'), ('age', 25), ('city', 'NYC')])

# Converting to a list
items_list = list(person.items())
print(items_list)  # [('name', 'Alice'), ('age', 25), ('city', 'NYC')]

# Iterating over items (most common)
for key, value in person.items():
    print(f"{key}: {value}")

# Dynamic view
person["email"] = "alice@example.com"
print(items)  # dict_items([('name', 'Alice'), ('age', 25), ('city', 'NYC'), ('email', 'alice@example.com')])

# Using in a list comprehension
keys_values = [(k, v) for k, v in person.items()]
print(keys_values)

# Filtering items
filtered = {k: v for k, v in person.items() if v is not None}
print(filtered)

Characteristics:

  • Returns a view object of (key, value) tuples
  • Dynamic — reflects changes to the dictionary
  • Most common method for iteration
  • Can be used in comprehensions

Quick Check: What does items() return when iterated? (Answer: (key, value) tuples)

get() — Safe Value Retrieval

4

Retrieving Values Safely

The get() method retrieves a value for a given key. If the key doesn't exist, it returns a default value (or None) instead of raising an error.

# Basic usage
person = {"name": "Alice", "age": 25}
print(person.get("name"))   # Alice
print(person.get("city"))   # None
print(person.get("city", "Unknown"))  # Unknown

# Using with default values
config = {"host": "localhost", "port": 8080}
print(config.get("host", "127.0.0.1"))    # localhost
print(config.get("timeout", 30))          # 30

# In a loop
keys = ["name", "age", "city", "country"]
for key in keys:
    value = person.get(key, "Not found")
    print(f"{key}: {value}")

# Practical use: counting with get()
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}

Characteristics:

  • Returns the value if the key exists
  • Returns None or a default value if the key doesn't exist
  • No error is raised
  • Ideal for safe data retrieval

Quick Check: What does get() return if the key is not found? (Answer: None or the specified default value)

update() — Merge Dictionaries

5

Merging Dictionaries

The update() method merges another dictionary or iterable of key-value pairs into the current dictionary. If keys already exist, their values are updated.

# Basic usage
person = {"name": "Alice", "age": 25}
person.update({"city": "NYC", "age": 26})
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'NYC'}

# Merging with another dictionary
data1 = {"a": 1, "b": 2}
data2 = {"b": 3, "c": 4}
data1.update(data2)
print(data1)  # {'a': 1, 'b': 3, 'c': 4}

# Using with keyword arguments
person.update(email="alice@example.com", phone="555-1234")
print(person)  # {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}

# Using with a list of tuples
person.update([("city", "LA"), ("age", 27)])
print(person)  # {'name': 'Alice', 'age': 27, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-1234'}

# Using with zip()
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {}
my_dict.update(zip(keys, values))
print(my_dict)  # {'a': 1, 'b': 2, 'c': 3}

Characteristics:

  • Modifies the dictionary in place
  • Accepts another dictionary, list of tuples, or keyword arguments
  • Returns None
  • Overwrites existing keys with new values

Quick Check: Does update() return a new dictionary? (Answer: No — it modifies the original in place)

pop() — Remove and Return

6

Removing a Key-Value Pair

The pop() method removes the specified key from the dictionary and returns its value. If the key doesn't exist, it returns a default value or raises KeyError.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
age = person.pop("age")
print(age)     # 25
print(person)  # {'name': 'Alice', 'city': 'NYC'}

# Using with a default value
city = person.pop("city", "Unknown")
print(city)    # NYC
country = person.pop("country", "USA")
print(country) # USA

# Without a default (raises KeyError)
# person.pop("country")  # KeyError: 'country'

# Safe popping
key_to_remove = "city"
if key_to_remove in person:
    value = person.pop(key_to_remove)
    print(f"Removed: {value}")
else:
    print("Key not found")

# Using pop in a loop
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
for key in list(person.keys()):
    if key != "name":
        person.pop(key)
print(person)  # {'name': 'Alice'}

Characteristics:

  • Removes and returns the value for the specified key
  • Raises KeyError if the key doesn't exist (no default)
  • Accepts an optional default value
  • Modifies the dictionary in place

Quick Check: What does pop() return? (Answer: The value of the removed key)

popitem() — Remove Last Item

7

Removing and Returning the Last Item

The popitem() method removes and returns the last inserted key-value pair from the dictionary. In Python 3.7+, this follows insertion order.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
item = person.popitem()
print(item)    # ('city', 'NYC')
print(person)  # {'name': 'Alice', 'age': 25}

# Removing all items using popitem()
person = {"name": "Alice", "age": 25, "city": "NYC"}
while person:
    key, value = person.popitem()
    print(f"Removed: {key} -> {value}")
print(person)  # {}

# popitem() on an empty dictionary
# empty = {}
# empty.popitem()  # KeyError: 'popitem(): dictionary is empty'

# Safe popitem with checking
if person:
    key, value = person.popitem()
    print(f"Removed: {key} -> {value}")
else:
    print("Dictionary is empty")

Characteristics:

  • Removes and returns the last inserted item
  • In Python 3.7+, follows insertion order
  • Raises KeyError if the dictionary is empty
  • Modifies the dictionary in place

Quick Check: What does popitem() return? (Answer: A (key, value) tuple)

clear() — Remove All

8

Removing All Key-Value Pairs

The clear() method removes all key-value pairs from the dictionary, leaving it empty.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(f"Before clear: {person}")

person.clear()
print(f"After clear: {person}")  # {}

# Checking if the dictionary is empty
if not person:
    print("Dictionary is empty")

# Clearing a dictionary in a loop
data = {"a": 1, "b": 2, "c": 3}
for key in list(data.keys()):
    data.pop(key)
print(data)  # {}

# Alternative: reassign to empty dictionary
data = {"a": 1, "b": 2, "c": 3}
data = {}  # Creates a new empty dictionary

Characteristics:

  • Removes all key-value pairs
  • Modifies the dictionary in place
  • Returns None
  • Useful for resetting a dictionary

Quick Check: What does clear() return? (Answer: None — it modifies the dictionary in place)

copy() — Create a Copy

9

Creating a Shallow Copy

The copy() method creates a shallow copy of the dictionary. Changes to the copy do not affect the original dictionary.

# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
copy = person.copy()
print(copy)  # {'name': 'Alice', 'age': 25, 'city': 'NYC'}

# Copy vs direct assignment
person = {"name": "Alice", "age": 25}
copy = person.copy()  # Creates a new dictionary
reference = person    # Reference to the same dictionary

copy["age"] = 30
reference["age"] = 35

print(person)  # {'name': 'Alice', 'age': 35} (reference changed)
print(copy)    # {'name': 'Alice', 'age': 30} (copy unaffected)

# Shallow copy with nested dictionaries
person = {"name": "Alice", "address": {"city": "NYC"}}
copy = person.copy()
copy["address"]["city"] = "LA"
print(person)  # {'name': 'Alice', 'address': {'city': 'LA'}} — nested changed!

# For deep copy, use copy module
import copy
person = {"name": "Alice", "address": {"city": "NYC"}}
deep_copy = copy.deepcopy(person)
deep_copy["address"]["city"] = "LA"
print(person)  # {'name': 'Alice', 'address': {'city': 'NYC'}} — unchanged

Characteristics:

  • Creates a shallow copy of the dictionary
  • Nested objects are not copied (they are referenced)
  • Use copy.deepcopy() for deep copies
  • Modifications to the copy don't affect the original

Quick Check: Does copy() create a deep copy? (Answer: No — it creates a shallow copy)

fromkeys() — Create from Keys

10

Creating a Dictionary from Keys

The fromkeys() class method creates a new dictionary from a sequence of keys, all with the same default value.

# Basic usage
keys = ["name", "age", "city"]
person = dict.fromkeys(keys)
print(person)  # {'name': None, 'age': None, 'city': None}

# With a default value
person = dict.fromkeys(keys, "unknown")
print(person)  # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

# Using with a list
keys = [1, 2, 3]
data = dict.fromkeys(keys, 0)
print(data)  # {1: 0, 2: 0, 3: 0}

# Using with a tuple
keys = ("a", "b", "c")
data = dict.fromkeys(keys, [])
print(data)  # {'a': [], 'b': [], 'c': []}

# Note: using mutable default values
data = dict.fromkeys(keys, [])
data["a"].append(1)
print(data)  # {'a': [1], 'b': [1], 'c': [1]} — all share the same list!

# To avoid this, use a comprehension
data = {key: [] for key in keys}
data["a"].append(1)
print(data)  # {'a': [1], 'b': [], 'c': []}

Characteristics:

  • Creates a new dictionary from keys
  • All keys have the same initial value
  • Works with any iterable of keys
  • Warning: Mutable default values are shared

Quick Check: What is the default value when using fromkeys() without specifying one? (Answer: None)

Common Mistakes

11

Watch Out For These!

Mistake 1: Using pop() Without Checking Key Existence

# WRONG — raises KeyError
person = {"name": "Alice", "age": 25}
# person.pop("city")  # KeyError

# CORRECT — use a default value
city = person.pop("city", "Unknown")
print(city)  # Unknown

Mistake 2: Assuming copy() Creates a Deep Copy

# WRONG — nested dictionaries are shared
person = {"name": "Alice", "address": {"city": "NYC"}}
copy = person.copy()
copy["address"]["city"] = "LA"
print(person)  # {'name': 'Alice', 'address': {'city': 'LA'}}

# CORRECT — use deepcopy
import copy
deep_copy = copy.deepcopy(person)

Mistake 3: Using fromkeys() with Mutable Default Values

# WRONG — all keys share the same list
keys = ["a", "b", "c"]
data = dict.fromkeys(keys, [])
data["a"].append(1)
print(data)  # {'a': [1], 'b': [1], 'c': [1]}

# CORRECT — use a comprehension
data = {key: [] for key in keys}

Quick Check: What is the most common mistake with fromkeys()? (Answer: Using mutable default values — they are shared across all keys)

Interactive Editor

Experiment with dictionary methods directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
DICTIONARY METHODS PRACTICE
========================================

Original: {'name': 'Alice', 'age': 25, 'city': 'NYC'}

1. KEYS()
Keys: ['name', 'age', 'city']

2. VALUES()
Values: ['Alice', 25, 'NYC']

3. ITEMS()
name: Alice
age: 25
city: NYC

4. GET()
get('name'): Alice
get('country', 'USA'): USA

5. UPDATE()
After update: {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com'}

6. POP()
Removed email: alice@example.com
After pop: {'name': 'Alice', 'age': 26, 'city': 'NYC'}

7. POPITEM()
Removed item: ('city', 'NYC')
After popitem: {'name': 'Alice', 'age': 26}

8. FROMKEYS()
From keys: {'x': 0, 'y': 0, 'z': 0}

9. CLEAR()
After clear: {}

Dictionary methods practice complete!
🏆

Certificate of Completion

You have completed the Python Dictionary Methods tutorial. You understand keys(), values(), items(), get(), update(), pop(), popitem(), clear(), copy(), and fromkeys() methods.

Quick Quiz — Test Your Knowledge

Let's see what you've learned about dictionary methods:

1. Which method returns all the keys in a dictionary?
2. What does the items() method return?
3. Which method merges two dictionaries?
4. What is the difference between pop() and popitem()?
5. What does the fromkeys() method do?

Frequently Asked Questions

What is the difference between keys() and items()? ▼

keys() returns only the keys, while items() returns key-value pairs as tuples. Use items() when you need both keys and values.

What is the difference between get() and dict[key]? ▼

dict[key] raises a KeyError if the key doesn't exist. get() returns None or a default value, without raising an error.

Does update() modify the original dictionary? ▼

Yes, update() modifies the dictionary in place and returns None.

What is the difference between copy() and deepcopy()? ▼

copy() creates a shallow copy (nested objects are shared). deepcopy() creates a recursive copy (nested objects are also copied).

What is the default value in fromkeys()? ▼

The default value is None if not specified: dict.fromkeys(keys).

Can I use pop() on an empty dictionary? ▼

pop() requires a key argument. On an empty dictionary, it raises KeyError for any key. popitem() raises KeyError on an empty dictionary.

Where to Go From Here

After mastering dictionary methods, consider exploring these related topics:

Iterate Dictionary

Learn different ways to loop through dictionaries.

Learn More →

Formatting Dictionaries

Learn how to format and display dictionaries.

Learn More →

Nested Dictionaries

Work with dictionaries within dictionaries.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Top PL SQL Interview Questions
Previous: Access Dictionary Items Next: Iterate Dictionary →