Table of Contents
Mapping types in Python, especially dictionaries, are powerful tools for organizing and retrieving data using key-value pairs. Unlike sequences where data is accessed by position, mappings allow access through meaningful identifiers - like names, categories, or IDs. Dictionaries are commonly used in real-world applications: from tracking inventory and user profiles to parsing JSON responses and building configurations. Mastering mapping types is a crucial step toward writing efficient, readable, and structured Python code. On this page, you’ll explore how to create, modify, query, and iterate through dictionaries using practical and realistic tasks.
You’ll begin with basic key-value manipulations and gradually move on to nested dictionaries, dynamic updates, and filtering logic.
To effectively solve the exercises on this page, make sure you're comfortable with the following concepts:
- Reading mapping type
-
Understanding Python data types (especially
dict
) - Declaring and using variables
-
Using operators like
in
,==
, and assignment - Valid names and reserved keywords
- Using
for
loops to iterate over data structures - Understanding basic functions like
len()
,dict.get()
,items()
, andkeys()
Beginner Level Practice – Mapping Type in Python
At the beginner level, the focus is on understanding what a dictionary is and how it behaves. These tasks introduce the basic syntax of key-value structures and show how to create, access, and update entries in a dictionary. You will learn to store structured data in a meaningful way using simple keys such as strings or integers. Beginners often find dictionaries powerful because they allow direct access to data by name - which is more intuitive than using indexes. These exercises provide a solid entry point into real-world applications like storing user info or mapping codes to descriptions.
Task 1. Phone Book Entry
Write a Python program that asks the user for a person's name and phone number, then stores this information in a dictionary where the name is the key and the phone number is the value. After that, print the dictionary.
What this Task Teaches
This task teaches how to create a dictionary, add a new key-value pair, and print the dictionary structure. It emphasizes how to use user input to dynamically populate a mapping and introduces dictionary assignment syntax.
Hints and Tips
- Use
input()
twice to get the name and phone number. - Declare an empty dictionary before adding data.
- Use square brackets to assign the value:
phone_book[name] = number
.
Common Mistakes
- Forgetting to initialize the dictionary: Trying to assign a value without creating the dictionary first leads to a
NameError
. - Using parentheses instead of square brackets:
dict(name) = number
is invalid. Always usedict[key]
syntax for assignment. - Reusing the same variable name: Overwriting the dictionary by assigning a string or number to the same variable can destroy your structure.
- Not using strings for keys: Be consistent and treat names as strings. Avoid using numbers as keys unless necessary.
-
Printing values only: Beginners often print just the value. Use
print(dict)
or iterate overitems()
to see both key and value.
Step-by-Step Thinking
You’re building a simple key-value lookup. Think of it as adding a record to a notebook where a name points to a phone number.
- Ask the user for a name and store it in a variable
- Ask the user for a phone number and store it
- Create an empty dictionary named
phone_book
- Add the name and number as a key-value pair
- Print the dictionary to verify it works
How to Make it Harder
- Ask for multiple entries using a loop
- Check if a name already exists and update it if needed
- Format the output nicely when displaying the dictionary
Task 2. Country Capitals
Create a dictionary that contains at least three countries and their capital cities. Print the dictionary. Then, ask the user to enter a country name and print the capital if the country exists in the dictionary.
What this Task Teaches
This task teaches how to retrieve values using a key and how to check for key existence in a dictionary. It also covers basic use of the in
operator and
conditional logic for user-friendly programs.
Hints and Tips
- Define a dictionary with a few key-value pairs manually
- Use
input()
to get the country name - Use
if country in dict
to check for a match - Use
dict[key]
orget()
to access the value
Common Mistakes
- Checking for a capital instead of the country: Make sure the user input is matched against the keys, not the values.
-
Not handling wrong input: If the user types an unknown country and you try to access it directly, it may cause a
KeyError
. Usein
to check first. -
Misspelling keys or mismatching case:
"France"
is different from"france"
. Normalize input with.title()
or.lower()
as needed. - Confusing key and value syntax: Remember:
dict[country]
gives you the capital, not the other way around. - Hardcoding too much: Beginners sometimes rewrite
if
conditions for every country. Use the dictionary lookup instead.
Step-by-Step Thinking
Think of the dictionary as a world atlas. You’re asking the user to name a country and looking up its capital in your reference.
- Create a dictionary like
{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo"}
- Ask the user to type a country name
- Check if the country is in the dictionary
- If it is, print the capital city
- If not, show a message like “Country not found”
How to Make it Harder
- Allow the user to keep searching until they type “exit”
- Make the check case-insensitive
- Let users add new country-capital pairs to the dictionary
Intermediate Level Practice – Mapping Type in Python
As you move into intermediate-level work with dictionaries, you'll go beyond static key-value assignments and start building dynamic logic that responds to user input or
processes multiple entries. These tasks involve modifying dictionary contents, counting values, and performing lookups in flexible and reusable ways. At this level, you'll also
learn to handle missing data, use methods like get()
, and iterate over dictionary items to transform or summarize information. This mirrors common patterns in data
parsing, user session tracking, and configuration management. The challenges here will help you get more comfortable writing code that adapts and scales with input.
Task 1. Word Frequency Counter
Ask the user to enter a sentence. Then, create a dictionary that counts how many times each word appears in the sentence. For example, for the input
"hello world hello"
, the output should be: {'hello': 2, 'world': 1}
.
What this Task Teaches
This task strengthens your ability to loop through elements, conditionally update dictionary values, and use dictionaries as counters. You will also work with string methods to split and clean user input.
Hints and Tips
- Use
.split()
to turn the sentence into words. - Loop through each word and check if it’s already in the dictionary.
- If the word exists, increment its count; otherwise, set it to 1.
- Use
dict.get(word, 0) + 1
as a shortcut to update counts.
Common Mistakes
-
Forgetting to initialize counts: If you don't check whether a word is already in the dictionary, you’ll get a
KeyError
when trying to increment a non-existent key. -
Case sensitivity issues: Words like "Hello" and "hello" are treated as different keys. Normalize all words using
.lower()
before counting. - Including punctuation: Words like
"hello!"
and"hello"
will be treated differently. Strip punctuation before counting. - Using a list instead of a dictionary: Some beginners try to store counts in a list. That doesn’t work - you need key-value pairing.
- Not printing the result clearly: Always show the final dictionary in a readable format to confirm your logic worked.
Step-by-Step Thinking
Imagine a word counter tool that tracks how often each word is spoken. That's exactly what your program will simulate.
- Ask the user for a sentence and store it as a string
- Split the sentence into individual words
- Initialize an empty dictionary to store word counts
- Loop through each word in the list
- Use
get()
to update the count or initialize it at 1 - Print the dictionary with word frequencies
How to Make it Harder
- Remove punctuation using
string.punctuation
andtranslate()
- Sort the result by word or frequency
- Ignore common stop words like "the", "and", "is", etc.
Task 2. Price Lookup System
Create a dictionary that maps product names to prices (e.g., {"apple": 0.5, "banana": 0.7, "milk": 1.2}
). Ask the user to input the name of a product. If it
exists, print the price. If it doesn't, print “Product not found”.
What this Task Teaches
This exercise develops your skill in validating dictionary keys, building simple lookup systems, and responding to user input in an informative way. It also reinforces the idea that dictionaries can model real-life databases or configurations.
Hints and Tips
- Predefine the dictionary with several key-value pairs
- Use
input()
to get the product name - Normalize the input with
.lower()
to match keys - Check for existence with
if name in dict
- Print the price if found; otherwise print a message
Common Mistakes
- Incorrect casing: The user might type "Milk" while your key is "milk". Always normalize the case before checking.
-
Using
[]
instead ofget()
without a check: Accessing a missing key with brackets will raise an error. Useget()
or check within
. - Returning the wrong value: Ensure you’re accessing the price (value), not printing the whole dictionary or a key.
- Forgetting to define the dictionary first: You must create and fill the product-price mapping before using it.
- Not handling empty or invalid input: Always prepare for cases where the user doesn’t type anything or enters a typo.
Step-by-Step Thinking
Think of this task like using a store’s product scanner. The user provides a name, and you search your "database" to return the price.
- Create a dictionary with product names and their prices
- Ask the user to input the product name
- Convert input to lowercase (if needed)
- Check if the product exists in the dictionary
- If it exists, print the price
- If it doesn’t, print “Product not found”
How to Make it Harder
- Allow the user to check multiple products in a loop
- Format prices with 2 decimal places using
format()
- Let the user add new products to the dictionary during runtime
Advanced Level Practice – Mapping Type in Python
At the advanced level, dictionary tasks simulate real-world problems such as nested data structures, user data aggregation, or merging and transforming mappings. You'll need to think critically about structure, nesting, and performance - and consider edge cases like missing values or inconsistent keys. These exercises challenge your ability to reason through multi-step workflows and encourage modular thinking by combining loops, conditions, and dictionary methods. Working at this level helps you transition from writing simple lookups to building tools that mimic real APIs, user tracking systems, and data parsing engines. Mastery here signals true comfort with one of Python’s most versatile data types.
Task 1. Grouping Students by Grade
You are given a list of student–grade pairs like [("Alice", "A"), ("Bob", "B"), ("Clara", "A"), ("Dan", "C")]
. Write a program that builds a dictionary where each
grade is a key and the value is a list of students who received that grade. The result should be something like:
{"A": ["Alice", "Clara"], "B": ["Bob"], "C": ["Dan"]}
.
What this Task Teaches
This task develops your understanding of grouped data processing and dictionary-based data aggregation. It strengthens your use of dict.setdefault()
or conditional
logic to build lists as dictionary values.
Hints and Tips
- Start with an empty dictionary.
- Loop through each (name, grade) tuple.
- Check if the grade already exists as a key.
- If it does, append the student; if not, create a new list.
Common Mistakes
-
Overwriting values instead of appending: Many beginners mistakenly assign
dict[grade] = name
instead of appending to a list, which causes data loss. - Forgetting to initialize the list: If you don’t check for the key before appending, you'll get a
KeyError
. - Confusing key and value roles: Ensure the grade is used as the dictionary key and the name is added to the list, not vice versa.
- Not using unpacking: Beginners often loop through the list incorrectly. Use
for name, grade in list
to avoid index confusion. - Printing the dictionary too early: Be sure to build the entire dictionary before printing the final result.
Step-by-Step Thinking
You're grouping students by their results - similar to how schools organize performance reports. The same principle applies to data clustering in analytics.
- Start with a list of (name, grade) tuples
- Create an empty dictionary called
grade_groups
- Loop over each tuple
- Check if the grade already exists in the dictionary
- If yes, append the name to the list
- If no, create a new list with that name
- Print the dictionary once all items are processed
How to Make it Harder
- Sort the list of students alphabetically inside each grade group
- Convert all grades to uppercase before grouping
- Use
collections.defaultdict
for cleaner logic
Task 2. Merge User Profiles
You are given two dictionaries with user profile data:
user1 = {"name": "Alice", "email": "This email address is being protected from spambots. You need JavaScript enabled to view it. "}
user2 = {"email": "alice_This email address is being protected from spambots. You need JavaScript enabled to view it. ", "age": 30}
Merge them into a single dictionary. In case of key conflicts, values from user2
should overwrite user1
. Print the final profile.
What this Task Teaches
This task teaches dictionary merging logic, how to manage conflicts between keys, and how to preserve and update important data. You’ll learn how to use
update()
method and dictionary unpacking with clarity and intent.
Hints and Tips
- Use
.update()
or dictionary unpacking to merge - Be aware of which values take precedence
- Print the dictionary after merging to check the result
- Copy
user1
first if you don’t want to modify the original
Common Mistakes
- Not copying before updating: If you use
user1.update(user2)
directly, you lose the original state ofuser1
. - Wrong precedence direction: Make sure that
user2
values overwriteuser1
- not the reverse. - Trying to use addition: Dictionaries cannot be added using
+
. Useupdate()
or unpacking instead. - Not checking key existence: You may want to log or alert when overwriting important fields like
email
. -
Accidentally merging into
user2
: Be clear about which object holds the final merged result.
Step-by-Step Thinking
Think of this as combining profile data from two systems. You want to retain the most up-to-date info without losing important fields.
- Start with two dictionaries:
user1
anduser2
- Create a copy of
user1
to preserve the original - Use
.update(user2)
to merge the two - Verify that
user2
's values overwrite where keys overlap - Print the merged dictionary
How to Make it Harder
- Track which fields were overwritten using a loop
- Only overwrite if the new value is not
None
or empty - Support deep merge for nested dictionaries