Python Activity
Python Activity
INDEX
DESCRIPTION PAGE NO
FEATURES:
It is an ordered collection that contains key - value pairs
separated by comma inside curly braces {}.
Each key is separated from its value by a colon ( : )
Dictionaries are ordered i.e. order of elements is preserved.
Dictionaries are changeable, means we can change, add or
remove items from the dictionary.
Duplicate keys are not allowed i.e. dictionaries cannot have 2
items with the same key.
Dictionary keys are case sensitive.
Keys must be single element.
Values in dictionary can be of any data type and can be
duplicated. Ex: list, tuple ,string, integer, etc
Dictionaries are indexed by keys.
Slicing concept is not supported.
1|Page
1. IDENTIFY USE CASES AND SOLVE THEM USING DICTIONARY.
Using dictionaries, We can solve various use cases efficiently. Here are
some use cases along with solutions using Python dictionaries:
Phone Book:
Use Case: Storing and retrieving phone numbers of contacts.
Solution :
phone_book = {
'Alice': '123-456-7890',
'Bob': '987-654-3210',
'Charlie': '555-555-5555'
# Retrieve Alice's phone number
alice_number = phone_book.get('Alice', 'Contact not found')
print(alice_number)
Product Catalog:
Use Case: Storing product information.
Solution :
Products = {
'item1': {'name': 'Product A', 'price': 10.99},
'item2': {'name': 'Product B', 'price': 15.49},
'item3': {'name': 'Product C', 'price': 5.99}
}
# Retrieve product information for item2
product_info = products.get('item2', 'Product not found')
print(product_info)
Inventory Tracking:
Use Case: Managing product quantities in an inventory.
Solution :
Inventory = {
'item1': 100,
'item2': 50,
'item3': 200
}
# Update item2 quantity
2|Page
Inventory['item2'] += 10
# Check quantity of item2
Print("Quantity of item2:", inventory['item2'])
Employee Database:
Use Case: Storing employee details.
Solution :
employees = {
'E001': {'name': 'Alice', 'position': 'Manager'},
'E002': {'name': 'Bob', 'position': 'Developer'},
'E003': {'name': 'Charlie', 'position': 'Designer'}
}
# Retrieve employee information for E002
employee_info = employees.get('E002', 'Employee not found')
print(employee_info)
Language Translation:
Use Case: Mapping words in one language to another.
Solution :
translations = {
'hello': 'hola',
'goodbye': 'adiós',
'thank you': 'gracias'
}
# Translate a word
word = "hello"
translated_word = translations.get(word, word)
print(translated_word)
Movie Ratings:
Use Case: Storing and retrieving movie ratings.
Solution :
movie_ratings = {
'MovieA': 4.5,
3|Page
'MovieB': 3.8,
'MovieC': 4.2
}
# Retrieve rating for MovieB
movie_rating = movie_ratings.get('MovieB', 'Rating not found')
print(movie_rating)
Book Library :
Use Case: Managing a library of books.
Solution :
library = {
'Book1': {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'},
'Book2': {'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'},
'Book3': {'title': '1984', 'author': 'George Orwell'}
}
# Retrieve book information for Book2
book_info = library.get('Book2', 'Book not found')
print(book_info)
Weather Forecast:
Use Case: Storing and retrieving weather forecasts for cities.
Solution :
weather_forecast = {
'New York': 'Partly Cloudy',
'Los Angeles': 'Sunny',
'Chicago': 'Rainy'
}
# Retrieve weather forecast for Chicago
forecast = weather_forecast.get('Chicago', 'Forecast not found')
print(forecast)
Quiz Scores:
Use Case: Storing and retrieving quiz scores.
Solution :
4|Page
quiz_scores = {
'Alice': [95, 88, 90],
'Bob': [75, 82, 93],
'Charlie': [88, 92, 96]
}
# Retrieve Alice's third quiz score
alice_score = quiz_scores.get('Alice', [])[2]
print(alice_score)
Student Information:
Use Case: Storing and retrieving student details.
Solution :
students = {
'Student1': {'name': 'Alice', 'age': 20, 'major': 'Computer Science'},
'Student2': {'name': 'Bob', 'age': 21, 'major': 'Mathematics'},
'Student3': {'name': 'Charlie', 'age': 19, 'major': 'Physics'}
}
# Retrieve information for Student2
student_info = students.get('Student2', 'Student not found')
print(student_info)
Account Balances:
Use Case: Storing and managing bank account balances.
Solution :
bank_accounts = {
'Account1': 5000.50,
'Account2': 2500.75,
'Account3': 10000.00
}
# Update balance for Account2
bank_accounts['Account2'] += 100.0
# Check balance for Account2
print("Balance for Account2:", bank_accounts['Account2'])
5|Page
Country Capitals:
Use Case: Storing and retrieving the capitals of countries.
Solution :
country_capitals = {
'USA': 'Washington, D.C.',
'France': 'Paris',
'Japan': 'Tokyo'
}
# Retrieve capital for France
capital = country_capitals.get('France', 'Capital not found')
print(capital)
Music Library:
Use Case: Managing a library of music tracks.
Solution :
music_library = {
'Track1': {'title': 'Song A', 'artist': 'Artist X'},
'Track2': {'title': 'Song B', 'artist': 'Artist Y'},
'Track3': {'title': 'Song C', 'artist': 'Artist Z'}
}
# Retrieve information for Track3
track_info = music_library.get('Track3', 'Track not found')
print(track_info)
Product Reviews:
Use Case: Storing and retrieving product reviews.
Solution :
product_reviews = {
'Product1': ['Excellent product!', 'Good value for money.'],
'Product2': ['Not as described.'],
'Product3': ['Highly recommended!']
}
# Retrieve reviews for Product2
reviews = product_reviews.get('Product2', 'No reviews available')
print(reviews)
6|Page
Dictionary of Dictionaries:
Use Case: Nested dictionaries for more complex data structures.
Solution :
data = {
'person1': {
'name': 'Alice',
'age': 25,
'address': {
'street': '123 Main St',
'city': 'New York'
}
},
'person2': {
'name': 'Bob',
'age': 30,
'address': {
'street': '456 Elm St',
'city': 'Los Angeles'
}
}
}
# Retrieve Alice's city
alice_city = data.get('person1', {}).get('address', {}).get('city', 'City not
found')
print(alice_city)
7|Page
2 . REIMPLIMENT BUILT IN DICTIONARY FUNCTIONS.
d.pop(key, default) - Removes and returns the value for a given key. If
the key is not found, it returns the default value.
def custom_pop(d, key, default=None):
if key in d:
value=d[key]
del d[key]
return value
8|Page
else:
return default
return list(d)
def custom_values(d):
if key not in d:
d[key] = default
def custom_clear(d):
del d[key]
9|Page
len(d) - Returns the number of key-value pairs in the dictionary.
def custom_len(d):
count = 0
for key in d:
count += 1
return count
for k in d:
if k == key:
return True
return False
def custom_copy(d):
new_dict = {}
10 | P a g e
new_dict[key] = value
return new_dict
new_dict = {}
new_dict[key] = value
return new_dict
11 | P a g e
3. IDENTIFY COMMON SYNTACTICAL ERRORS WHEN WORKING WITH
DICTIONARY.
Missing Colons: When defining key-value pairs, make sure to use colons
to separate keys and values.
Unmatched Quotes: Keys and string values should have matching quotes
(single or double).
Extra Commas: Don't add an extra comma after the last key-value pair in
the dictionary.
12 | P a g e
my_dict = {'class': 'Python'} # 'class' is a reserved word
To avoid this, use get() or check for key existence before accessing.
Mixing Data Types: Ensure that dictionary keys are of the same data
type (e.g., don't mix strings and integers).
my_key = 'a'
13 | P a g e
Accessing Keys with Attributes: Be cautious of accessing dictionary
keys using attributes (e.g., my_dict.key), which can lead to AttributeError.
Using Incompatible Data Types: Make sure you use compatible data
types for keys and values. For instance, avoid using lists as keys.
my_dict = {'a': 1,
def my_function():
def my_function():
without escaping
14 | P a g e
Using Variables as Keys Without Quotes: Don't use variable names
as keys without enclosing them in quotes.
key = 'a'
Multiple Keys with the Same Name: Dictionary keys must be unique;
you can't have duplicate keys.
15 | P a g e