Python Dictionaries

Python Dictionary is a fundamental data structure that plays a crucial role in programming. This article explains what dictionaries are, their key features, and how to use them in Python. It also explores their benefits and practical applications to provide a comprehensive understanding of Python dictionaries.

Contents:

  1. Introduction to Python Dictionaries
  2. Creating a Dictionary in Python
  3. Accessing Dictionary Elements in Python
  4. Adding Elements to a Dictionary in Python
  5. Removing Elements from a Dictionary in Python
  6. Modifying Dictionary Elements in Python
  7. Dictionary Methods in Python
  8. Dictionary Functions in Python
  9. Iterating Through a Dictionary in Python
  10. Dictionary Comprehension
  11. Nested Dictionaries in Python
  12. FAQs on Python Dictionaries

Introduction to Python Dictionaries

In Python, a dictionary is a built-in data structure that allows you to store key-value pairs. It is highly efficient for retrieving values when the key is known.

Key Features of Dictionaries:

  • Mutable – Can add, modify, or remove items.
  • Unique & Immutable Keys – Keys must be unique and immutable (e.g., strings, numbers).
  • Fast Lookups – Optimized for quick data retrieval.
  • Supports Nesting – Can contain other dictionaries.
  • Unordered – Maintains insertion order.

Creating a Dictionary in Python

A dictionary in Python is created using curly braces {} or by using the dict() function. It stores key-value pairs where each key is unique and maps to a specific value.

advertisement

1. Using Curly Braces {}

# Dictionary with subject names and marks
subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
print(subjects)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85, 'AI': 98}

2. Using dict() Constructor

🎓 Free Certifications on 300 subjects are live for December 2025. Register Now!

Use empty {} or dict() to create an empty dictionary.

# Using empty braces
empty_dict = {}
 
# Using dict() function
empty_dict2 = dict()
 
print(empty_dict)
print(empty_dict2)

Output:

{}
{}

3. Using dict() with Key-Value Pairs

advertisement

Pass key-value pairs as arguments to dict().

# Creating dictionary using dict()
quiz_scores = dict(Python=95, Java=90, DBMS=85)
print(quiz_scores)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85}

4. Creating a Dictionary Using Tuples

Convert a list of tuples into a dictionary.

# List of tuples to dictionary
subject_list = [("Python", 95), ("Java", 90), ("DBMS", 85)]
subjects_from_list = dict(subject_list)
print(subjects_from_list)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85}

5. Dictionary Comprehension

squares = {x: x**2 for x in range(1, 4)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9}

Accessing Dictionary Elements in Python

Dictionaries store data in key-value pairs where each key maps to a specific value. You can access dictionary elements by referring to the key.

1. Accessing Using Key Name

Use square brackets [] with the key name to access the value.

# Dictionary of subject marks
subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
 
# Accessing values using keys
print(subjects["Python"]) 
print(subjects["AI"])

Output:

95
98

2. Accessing Using get() Method

The get() method retrieves the value of a specified key. It returns None if the key is not found, preventing errors.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
# Using get() method
print(subjects.get("Java"))
print(subjects.get("ML"))

Output:

90
None

3. Accessing All Keys Using keys() Method

The keys() method returns a list of all keys in the dictionary.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
# Get all keys
print(subjects.keys())

Output:

dict_keys(['Python', 'Java', 'DBMS', 'AI'])

4. Accessing All Values Using values() Method

The values() method returns a list of all values.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
# Get all values
print(subjects.values())

Output:

dict_values([95, 90, 85, 98])

5. Accessing Key-Value Pairs Using items() Method

The items() method returns a list of tuples with key-value pairs.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85,
    "AI": 98
}
# Get all key-value pairs
print(subjects.items())

Output:

dict_items([('Python', 95), ('Java', 90), ('DBMS', 85), ('AI', 98)])

Adding Elements to a Dictionary in Python

Dictionaries in Python allow adding new key-value pairs dynamically. You can add elements using assignment or the update() method.

1. Adding a Single Key-Value Pair

Use square brackets [] with a new key and assign a value.

# Dictionary of subject marks
subjects = {
    "Python": 95,
    "Java": 90
}
 
# Adding a new subject
subjects["DBMS"] = 85
print(subjects)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85}

2. Adding Multiple Key-Value Pairs Using update()

The update() method allows adding multiple key-value pairs at once.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85
}
# Adding multiple subjects
subjects.update({"AI": 98, "Cyber Security": 91})
print(subjects)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85, 'AI': 98, 'Cyber Security': 91}

3. Adding Elements to an Empty Dictionary

Start with an empty dictionary and add elements dynamically.

# Creating an empty dictionary
quiz_scores = {}
 
# Adding subjects and marks
quiz_scores["Python"] = 95
quiz_scores["Java"] = 90
print(quiz_scores)

Output:

{'Python': 95, 'Java': 90}

4. Using dict() to Add Key-Value Pairs

Use dict() to create and add key-value pairs.

subjects = {
    "Python": 95,
    "Java": 90,
    "DBMS": 85
}
# Adding using dict()
extra_subjects = dict(ML=88, IoT=87)
subjects.update(extra_subjects)
print(subjects)

Output:

{'Python': 95, 'Java': 90, 'DBMS': 85, 'ML': 88, 'IoT': 87}

Removing Elements from a Dictionary in Python

Dictionaries in Python provide multiple methods to remove elements based on keys or conditions. You can delete a single item, multiple items, or even clear the entire dictionary.

1. Using del to Remove a Key-Value Pair

del removes an element by specifying the key.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Removing 'Java' using del
del subjects["Java"]
print("After using del:", subjects)

Output:

After using del: {'Python': 95, 'DBMS': 85, 'AI': 98}

2. Using pop() to Remove and Return a Value

pop() removes a key and returns the corresponding value.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Removing 'DBMS' using pop()
removed_marks = subjects.pop("DBMS")
print("Removed Marks using pop():", removed_marks)
print("After using pop():", subjects)

Output:

Removed Marks using pop(): 85
After using pop(): {'Python': 95, 'Java': 90, 'AI': 98}

3. Using popitem() to Remove the Last Inserted Pair

popitem() removes and returns the last inserted key-value pair.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Removing the last inserted element using popitem()
last_removed = subjects.popitem()
print("Last Removed using popitem():", last_removed)
print("After using popitem():", subjects)

Output:

Last Removed using popitem(): ('AI', 98)
After using popitem(): {'Python': 95, 'Java': 90, 'DBMS': 85}

4. Removing Elements Conditionally Using a Loop

Remove elements that meet a certain condition using a loop.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Removing subjects with marks below 90
for key in list(subjects.keys()):
    if subjects[key] < 90:
        del subjects[key]
 
print("After conditional deletion:", subjects)

Output:

After conditional deletion: {'Python': 95, 'Java': 90, 'AI': 98}

5. Using clear() to Remove All Elements

clear() removes all elements, leaving an empty dictionary.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Clearing the dictionary
subjects.clear()
print("After using clear():", subjects)

Output:

After using clear(): {}

Modifying Dictionary Elements in Python

1. Modifying a Single Element

To modify an element, assign a new value to the key.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
# Modifying marks of 'Java'
subjects["Java"] = 92
print("After modifying Java marks:", subjects)

Output:

After modifying Java marks: {'Python': 95, 'Java': 92, 'DBMS': 85, 'AI': 98}

2. Modifying Multiple Elements Using update()

update() modifies multiple elements or adds new elements if the key does not exist.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
# Modifying multiple elements
subjects.update({"DBMS": 88, "AI": 99})
print("After modifying multiple elements:", subjects)

Output:

After modifying multiple elements: {'Python': 95, 'Java': 90, 'DBMS': 88, 'AI': 99}

3. Modifying Using a Loop

Modify dictionary elements based on conditions in a loop.

# Creating a dictionary with subjects and marks
subjects = {"Python": 95, "Java": 92, "DBMS": 88, "AI": 99}
# Increasing marks by 5 if marks are less than 95
for key in subjects:
    if subjects[key] < 95:
        subjects[key] += 5
 
print("After increasing marks:", subjects)

Output:

After increasing marks: {'Python': 95, 'Java': 97, 'DBMS': 93, 'AI': 99}

Dictionary Methods in Python

Python provides several built-in methods to manipulate dictionaries. These methods help in retrieving, modifying, and managing key-value pairs effectively.

Method Description Example
keys() Returns all keys in the dictionary dict.keys()
values() Returns all values in the dictionary dict.values()
items() Returns all key-value pairs as tuples dict.items()
get(key) Retrieves value of a key safely dict.get(“key”, “default”)
update() Adds or updates multiple key-value pairs dict.update({“key”: “value”})
pop(key) Removes a key and returns its value dict.pop(“key”)
popitem() Removes and returns the last inserted item dict.popitem()
setdefault() Returns value of a key or sets a default value dict.setdefault(“key”, “default”)
clear() Removes all elements from the dictionary dict.clear()
copy() Returns a shallow copy of the dictionary dict.copy()

Dictionary Functions in Python

Here are several built-in functions that work with dictionaries, along with examples:

Function Description Example
len(dict) Returns the number of key-value pairs in the dictionary. len(student)
all(dict) Returns True if all keys are truthy or the dictionary is empty. all({1: “A”, 2: “B”})
any(dict) Returns True if at least one key is truthy. any({0: “”, 1: “A”})
sorted(dict) Returns a sorted list of dictionary keys. sorted({“b”: 2, “a”: 1})
max(dict) Returns the key with the highest value. max({“a”: 1, “b”: 2})
min(dict) Returns the key with the lowest value. min({“a”: 1, “b”: 2})
sum(dict.values()) Returns the sum of all values (if numeric). sum({“a”: 10, “b”: 20}.values())
dict() Creates a new dictionary. dict(a=1, b=2)
enumerate(dict) Returns an enumerate object of dictionary keys. list(enumerate({“a”: 1, “b”: 2}))
reversed(dict) Returns a reversed iterator of dictionary keys. list(reversed({“a”: 1, “b”: 2}))

Iterating Through a Dictionary in Python

Dictionaries store key-value pairs and provide multiple ways to iterate over them to access keys, values, or both.

1. Iterating Through Keys

Use a for loop to iterate through dictionary keys.

subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
 
for sub in subjects:
    print(sub)

Output:

Python  
Java  
DBMS  
AI

2. Iterating Through Values

subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
for marks in subjects.values():
    print(marks)

Output:

95  
90  
85  
98

3. Iterating Through Key-Value Pairs

subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
for sub, marks in subjects.items():
    print(sub, "->", marks)

Output:

Python -> 95  
Java -> 90  
DBMS -> 85  
AI -> 98

4. Using enumerate() with Keys

subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
for i, sub in enumerate(subjects):
    print(i, sub)

Output:

0 Python  
1 Java  
2 DBMS  
3 AI

5. Iterating Using Dictionary Comprehension

subjects = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
new_subjects = {sub: marks + 5 for sub, marks in subjects.items()}
print(new_subjects)

Output:

{'Python': 100, 'Java': 95, 'DBMS': 90, 'AI': 103}

Dictionary Comprehension

Dictionary comprehension provides a concise way to create dictionaries by iterating through iterable objects and applying logic to generate key-value pairs in a single line.

Syntax of Dictionary Comprehension

new_dict = {key: value for key, value in iterable}

1. Creating a Dictionary with Squared Values

Generate a dictionary with numbers and their squares.

squares = {x: x**2 for x in range(1, 5)}
print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16}

2. Creating a Dictionary from a List

Convert a list of subjects to a dictionary with default marks.

subjects = ["Python", "Java", "DBMS", "AI"]
marks = {sub: 95 for sub in subjects}
print(marks)

Output:

{'Python': 95, 'Java': 95, 'DBMS': 95, 'AI': 95}

3. Filtering Elements in Dictionary Comprehension

Create a dictionary with only even numbers.

even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)

Output:

{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

4. Using if-else in Dictionary Comprehension

Apply conditions in value assignment.

subjects_marks = {"Python": 95, "Java": 90, "DBMS": 85, "AI": 98}
marks = {sub: ("Pass" if score >= 90 else "Fail") for sub, score in subjects_marks.items()}
print(marks)

Output:

{'Python': 'Pass', 'Java': 'Pass', 'DBMS': 'Fail', 'AI': 'Pass'}

Nested Dictionaries in Python

A nested dictionary is a dictionary inside another dictionary, allowing multiple layers of information.

1. Creating a Nested Dictionary

students = {
    "John": {"Python": 90, "Java": 85},
    "Emma": {"Python": 95, "Java": 92}
}
print(students)

Output:

{'John': {'Python': 90, 'Java': 85}, 'Emma': {'Python': 95, 'Java': 92}}

2. Accessing and Modifying Elements

students = {
    "John": {"Python": 90, "Java": 85},
    "Emma": {"Python": 95, "Java": 92}
}
print(students["John"]["Python"])  # Output: 90
students["Emma"]["Java"] = 94
print(students["Emma"])  # Output: {'Python': 95, 'Java': 94}

3. Iterating Through Nested Dictionaries

students = {
    "John": {"Python": 90, "Java": 85},
    "Emma": {"Python": 95, "Java": 92}
}
for name, subjects in students.items():
    for sub, marks in subjects.items():
        print(f"{name} - {sub}: {marks}")

Output:

John - Python: 90
John - Java: 85
John - DBMS: 89
Emma - Python: 95

FAQs on Python Dictionaries

1. What is a dictionary in Python?
A dictionary is a data structure that stores key-value pairs, where each key is unique and maps to a specific value.

2. How do you access values in a dictionary?
You can access values by using their keys. If the key does not exist, an error may occur unless you use a safe retrieval method.

3. How do you add or modify dictionary elements?
You can add a new key-value pair or update an existing key’s value by assigning it a new value.

4. How do you merge two dictionaries?
Dictionaries can be merged using built-in methods, allowing you to combine multiple key-value pairs into one dictionary.

5. What is a nested dictionary?
A nested dictionary is a dictionary that contains other dictionaries as values, allowing for hierarchical data storage.

6. Can dictionary keys be of any data type?
Dictionary keys must be of an immutable data type, such as strings, numbers, or tuples, while values can be of any type.

Key Points to Remember

Here is the list of key points we need to remember about “Python Dictionaries”.

  • Python dictionaries store data in key-value pairs, making them useful for fast and efficient data retrieval. Unlike lists or tuples, which use numerical indexing, dictionaries use keys, allowing for more meaningful data associations.
  • Dictionaries are mutable, meaning their contents can be changed after creation. You can add, modify, or remove key-value pairs dynamically without creating a new dictionary.
  • Keys must be unique and immutable, meaning they can be strings, numbers, or tuples but not lists or other dictionaries. Duplicate keys overwrite previous values rather than creating new entries.
  • Dictionary methods like keys(), values(), and items() allow easy retrieval of keys, values, and key-value pairs, respectively. These methods return iterable views, which can be converted into lists if needed.
  • Elements can be accessed using dict[key], get(), keys(), values(), and items() to retrieve keys, values, and key-value pairs efficiently.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.