</> Code Editor { } Code Formatter

Python Dictionaries Exercises


1/20

Python Dictionaries Practice Questions

Correct
0%

Which of the following statements about Python dictionaries is true?


Let’s carefully understand the basics of Python dictionaries:

  • Dictionaries are unordered collections (in Python 3.7+, they preserve insertion order, but not sorted order).
  • Keys in a dictionary must be unique. If a duplicate key is added, the latest value overwrites the old one.
  • Keys must be immutable types such as strings, numbers, or tuples. Mutable types like lists are not allowed.
  • Correct Option: 4 → Dictionaries are mutable (can be changed after creation) and store key-value pairs with unique keys.

Key takeaway: Think of a dictionary like a real-life dictionary – every word (key) must be unique, and each word has exactly one meaning (value).

Quick Recap of Python Dictionaries Concepts

If you are not clear on the concepts of Dictionaries, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.

What Is a Python Dictionary

A Python dictionary is a collection of key-value pairs, where each key is unique and immutable (e.g., string, number, tuple) and maps to a value, which can be of any data type. Dictionaries let you store and retrieve data efficiently using the key. Since Python 3.7, dictionaries maintain insertion order.

Creating Python Dictionaries

You can create a dictionary using curly braces {}, the dict() constructor, or from iterables of key-value pairs:

person = {"name": "Rina", "age": 28, "country": "Bangladesh"}
config = dict(mode="auto", version=3.12, debug=False)
empty = {}
tags = dict([("lang", "Python"), ("level", "intermediate")])

Accessing and Retrieving Values

You can access dictionary values using keys or the get() method for safe retrieval:

settings = {"theme": "dark", "font_size": 14, "show_line_numbers": True}

print(settings["theme"])           # dark
print(settings.get("font_size"))   # 14

# Safe retrieval using get() to avoid KeyError
print(settings.get("auto_save", False))  # returns False if key not found

Adding, Updating, and Removing Items

Dictionaries are mutable: you can add new key-value pairs, update existing ones, or remove entries.

data = {"id": 101, "name": "Samir"}
# Add new key-value
data["role"] = "editor"

# Update existing value
data["name"] = "Samir Ahmed"

# Remove by key
del data["id"]

# Remove and return value
age = data.pop("age", None)

# Clear the dictionary
data.clear()

Built-in Dictionary Methods & Operations

Python dictionaries provide many useful methods for data access, modification, and iteration:

Method / FunctionDescription
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of (key, value) pairs
get(key, default)Retrieves value for key; returns default if key not found
pop(key[, default])Removes key and returns its value (or default if key absent)
popitem()Removes last inserted key-value pair
clear()Removes all items from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys(seq, default=None)Creates a new dict with keys from seq, each assigned default
dict comprehensionCreate dict dynamically: {x: x*x for x in range(1,6)}

Iterating Over a Dictionary

You can iterate over keys, values, or key-value pairs:

user = {"username": "maya", "score": 85, "level": 3}

# Looping keys
for key in user.keys():
    print(key)

# Looping values
for value in user.values():
    print(value)

# Looping key-value pairs
for key, value in user.items():
    print(key, ":", value)

Nested Dictionaries & Using Complex Data

Dictionaries can contain other dictionaries or lists, useful for structured data:

employee = {
    "id": 501,
    "name": "Tanvir",
    "profile": {
        "department": "HR",
        "skills": ["communication", "management"]
    }
}
print(employee["profile"]["skills"][1])  # management

When to Use Dictionary: Use Cases & Advantages

  • Fast lookup by key — average O(1) time for search, insert, delete
  • Represent structured data with named attributes (e.g., user info, configuration settings)
  • Dynamic and flexible — easy to add, update, or remove key-value pairs
  • Useful for counting/frequency tasks (word count, tally, mapping IDs to objects)
  • Merging or combining data sources with unique keys

Limitations and Constraints of Dictionaries

  • Keys must be immutable (strings, numbers, tuples, etc.); mutable types like lists or dicts cannot be used as keys
  • Duplicate keys are not allowed — assigning a duplicate key overwrites the existing value
  • Cannot use non-hashable objects as keys

Summary: Key Takeaways

  • Dictionaries are collections of unique keys mapped to values
  • Flexible creation: literal {}, dict() constructor, or comprehension
  • Supports dynamic operations: add, update, delete, copy, clear
  • Powerful built-in methods for data access, retrieval, iteration, and transformation
  • Ideal for structured data, frequency maps, configuration/data storage, and fast lookups


About This Exercise: Python Dictionaries Exercises

Welcome to Solviyo’s Python Dictionaries exercises, designed to help you master one of Python’s most flexible and powerful data structures. Dictionaries store data as key-value pairs, enabling fast lookups, efficient updates, and clear mappings. These exercises provide hands-on practice and interactive MCQs to ensure you understand both syntax and practical usage.

What You Will Learn

In this set of Python Dictionaries exercises, you will explore:

  • Creating dictionaries and accessing values using keys.
  • Adding, updating, and removing dictionary entries.
  • Iterating through dictionaries using keys, values, and items.
  • Using built-in methods like get(), items(), update(), and dictionary comprehensions.
  • Applying dictionaries to real-world problems such as counting word frequencies, mapping IDs to values, and grouping data.
  • Reinforcing learning with interactive MCQs to understand common pitfalls and interview-style questions.
  • Writing clean, efficient, and optimized dictionary code for practical Python applications.

Why Learning Python Dictionaries Matters

Dictionaries are a fundamental part of Python programming. Mastering them allows you to efficiently store and retrieve data, write concise and maintainable code, and solve real-world problems effectively. Understanding dictionaries prepares you for advanced topics, coding interviews, and professional Python development.

Start Practicing Python Dictionaries Today

By completing these exercises, you will gain confidence in using Python dictionaries for a wide range of tasks. Each exercise includes detailed explanations to reinforce learning and help you apply concepts correctly. Start practicing Python Dictionaries exercises now, and build a strong foundation in Python data structures for real-world programming success.