0% found this document useful (0 votes)
20 views

Python Activity

This document discusses dictionaries in Python. It begins with an overview of dictionaries and their features, such as storing data in key-value pairs and being unordered, changeable collections that do not allow duplicate keys. Several common use cases for dictionaries are then presented and solved using Python dictionaries, such as a phone book, product catalog, and employee database. Built-in dictionary functions like update(), fromkeys(), popitem(), and pop() are then reimplemented. Finally, common syntactical errors with dictionaries are identified.

Uploaded by

Chaitra kharvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Activity

This document discusses dictionaries in Python. It begins with an overview of dictionaries and their features, such as storing data in key-value pairs and being unordered, changeable collections that do not allow duplicate keys. Several common use cases for dictionaries are then presented and solved using Python dictionaries, such as a phone book, product catalog, and employee database. Built-in dictionary functions like update(), fromkeys(), popitem(), and pop() are then reimplemented. Finally, common syntactical errors with dictionaries are identified.

Uploaded by

Chaitra kharvi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

EXPERIMENT NO : 7

INDEX

DESCRIPTION PAGE NO

 About dictionary and it’s features. 0-1

 Identify use cases and solve them


2-7
using dictionary.

 Reimpliment built in dictionary


8-11
functions.

 Identify common syntactical errors


12-15
when working with dictionary.
DICTIONARY IN PYTHON
ABOUT :
 Dictionaries are used to store data values in key-value pairs.
 A dictionary is a collection which is ordered, changeable and
do not allow duplicates.
 Dictionaries are Python’s implementation of a data
structure that is more generally known as an associative
array.
 You can also construct a dictionary with the built-in dict()
function.
 Once you’ve defined a dictionary, you can display its
contents, the same as you can do for a list.
 A dictionary consists of a collection of key-value pairs. Each
key-value pair maps the key to its associated value.
 Dictionaries are written with flower brackets { }.

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.

Here are the some reimplementation of dictionary functions.


 d.update(other) - Updates the dictionary with key-value pairs from
another dictionary or iterable.
def custom_update(d, other):
for key, value in other.items():
d[key] = value

 d.fromkeys(keys, value=None) - Creates a new dictionary with the


specified keys and an optional default value.
def custom_fromkeys(keys, value=None):
new_dict = {}
for key in keys:
new_dict[key] = value
return new_dict

 d.popitem() - Removes and returns an arbitrary key-value pair as a tuple.


def custom_popitem(d):
if not d:
raise KeyError("popitem(): dictionary is empty")
key = next(iter(d))
value = d[key]
del d[key]
return (key , value)

 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

 d.items() - Returns a view of all key-value pairs in the dictionary.


def custom_items(d):
return [(key, d[key]) for key in d]

 d.keys() - Returns a view of all keys in the dictionary.


def custom_keys(d):

return list(d)

 d.values() - Returns a view of all values in the dictionary.

def custom_values(d):

return [d[key] for key in d]

 d.setdefault(key, default) - Returns the value for a given key or sets a


default value if the key is not found.

def custom_setdefault(d, key, default=None):

if key not in d:

d[key] = default

 return d[key]d.clear() - Removes all key-value pairs from the


dictionary.

def custom_clear(d):

for key in list(d.keys()):

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

 key in d - Checks if a key is present in the dictionary. Returns True or False.

def custom_contains_key(d, key):

for k in d:

if k == key:

return True

return False

 d.get(key, default=None) - Returns the value for a given key or a


default value if the key is not found.

def custom_get(d, key, default=None):

return d[key] if key in d else default

 d.copy() - Returns a shallow copy of the dictionary.

def custom_copy(d):

new_dict = {}

for key, value in d.items():

10 | P a g e
new_dict[key] = value

return new_dict

 d.fromkeys(keys, value=None) - Creates a new dictionary with the


specified keys and an optional default value.

def custom_fromkeys(keys, value=None):

new_dict = {}

for key in keys:

new_dict[key] = value

return new_dict

11 | P a g e
3. IDENTIFY COMMON SYNTACTICAL ERRORS WHEN WORKING WITH
DICTIONARY.

Some common syntactical errors when working with dictionaries :

 Missing Colons: When defining key-value pairs, make sure to use colons
to separate keys and values.

my_dict = {'a' 1, 'b' 2} # Missing colons

 Misplaced Commas: Ensure you have commas between key-value pairs


and not other punctuation marks.

my_dict = {'a': 1 'b': 2} # Missing commas

 Using Square Brackets: Dictionary keys should be enclosed in curly


braces, not square brackets.

my_dict = ['a': 1, 'b': 2] # Incorrect use of square brackets

 Unmatched Quotes: Keys and string values should have matching quotes
(single or double).

my_dict = {"a': 1, 'b': 2} # Unmatched quotes for 'a'

 Extra Commas: Don't add an extra comma after the last key-value pair in
the dictionary.

my_dict = {'a': 1, 'b': 2, } # Extra comma at the end

 Using Reserved Words: Avoid using Python's reserved words as


dictionary keys.

12 | P a g e
my_dict = {'class': 'Python'} # 'class' is a reserved word

 Accessing a Nonexistent Key: When accessing dictionary values,


ensure the key exists to avoid a KeyError.

my_dict = {'a': 1, 'b': 2}

value = my_dict['c'] # Raises KeyError

To avoid this, use get() or check for key existence before accessing.

value = my_dict.get('c', 0) # Default to 0 if 'c' doesn't exist

 Mixing Data Types: Ensure that dictionary keys are of the same data
type (e.g., don't mix strings and integers).

my_dict = {'a': 1, 2: 'b'} # Mixing data types for keys

 Variable Names in Keys: Don't use variable names as dictionary keys


without quotes.

my_key = 'a'

my_dict = {my_key: 42} # Using variable name without quotes

 Not Using Dictionaries Correctly: Avoid trying to access values or


keys as if they were attributes of an object.

my_dict = {'a': 1, 'b': 2}

value = my_dict.a # Raises AttributeError

To access dictionary values, use square brackets.

value = my_dict['a'] # Correct way to access '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.

my_dict = {'a': 1, 'b': 2}

value = my_dict.a # Raises 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, 'b': 2} # Using a list as a key

 Misaligned Key-Value Pairs: Ensure that key-value pairs in the


dictionary are properly aligned.

my_dict = {'a': 1,

'b': 2} # Misaligned key-value pairs

 Indentation Errors: When defining dictionaries inside code blocks (e.g.,


functions or loops), ensure correct indentation.

def my_function():

my_dict = {'a': 1, 'b': 2} # Correct indentation

def my_function():

my_dict = {'a': 1, 'b': 2} # Incorrect indentation

 Using Reserved Characters in Keys: Avoid using reserved characters


like '@', '-', and '/' in keys without appropriate escaping.

my_dict = {'[email protected]': 'user'} # Using '@' in a key

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'

my_dict = {key: 1} # Using variable 'key' without quotes

 Multiple Keys with the Same Name: Dictionary keys must be unique;
you can't have duplicate keys.

my_dict = {'a': 1, 'a': 2} # Duplicate key 'a'

 Nesting Dictionaries Incorrectly: When nesting dictionaries, ensure


that you use the correct syntax.

my_dict = {'a': {'b': 1, 'c': 2}, 'd': 3} # Correct nesting

my_dict = {'a': {'b': 1, 'c': 2}, 'd': 3 # Incorrect nesting

15 | P a g e

You might also like