Certainly! Below are some sample Python lab programs focused on dictionaries and their operations, along with a detailed explanation of how the code is executed.
1. Creating and Accessing Elements in a Dictionary
Objective: Learn how to create a dictionary and access its elements.
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Accessing elements by key
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
Explanation:
person = {}
: A dictionary is created with three key-value pairs, where"name"
,"age"
, and"city"
are keys, and"John"
,30
, and"New York"
are their corresponding values.person['name']
: This accesses the value associated with the key"name"
.person['age']
: This accesses the value associated with the key"age"
.- Output:
Name: John
Age: 30
2. Adding, Updating, and Removing Key-Value Pairs
Objective: Learn how to add, update, and remove key-value pairs in a dictionary.
# Creating a dictionary
person = {
"name": "John",
"age": 30
}
# Adding a new key-value pair
person["city"] = "New York"
print(f"Updated dictionary: {person}")
# Updating an existing key-value pair
person["age"] = 31
print(f"Updated age: {person['age']}")
# Removing a key-value pair
del person["city"]
print(f"Dictionary after removing 'city': {person}")
Explanation:
person["city"] = "New York"
: Adds a new key"city"
with the value"New York"
to the dictionary.person["age"] = 31
: Updates the value of the"age"
key from30
to31
.del person["city"]
: Deletes the key-value pair associated with the"city"
key from the dictionary.- Output:
Updated dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}
Updated age: 31
Dictionary after removing 'city': {'name': 'John', 'age': 31}
3. Iterating Over a Dictionary
Objective: Learn how to iterate through keys, values, and key-value pairs of a dictionary.
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Iterating over keys
for key in person:
print(f"Key: {key}")
# Iterating over values
for value in person.values():
print(f"Value: {value}")
# Iterating over key-value pairs
for key, value in person.items():
print(f"Key: {key}, Value: {value}")
Explanation:
for key in person:
: This loop iterates over the keys in the dictionary.for value in person.values():
: This loop iterates over the values in the dictionary.for key, value in person.items():
: This loop iterates over both keys and values in the dictionary using theitems()
method.- Output:
- Keys:
name
,age
,city
- Values:
John
,30
,New York
- Key-Value Pairs:
name: John
,age: 30
,city: New York
- Keys:
4. Checking if a Key Exists in a Dictionary
Objective: Learn how to check if a key exists in a dictionary using in
.
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Checking if a key exists
if "name" in person:
print("The key 'name' exists in the dictionary.")
if "country" not in person:
print("The key 'country' does not exist in the dictionary.")
Explanation:
if "name" in person:
: This checks if the key"name"
exists in the dictionaryperson
.if "country" not in person:
: This checks if the key"country"
does not exist in the dictionary.- Output:
The key 'name' exists in the dictionary.
The key 'country' does not exist in the dictionary.
5. Nested Dictionaries
Objective: Learn how to work with nested dictionaries.
# Creating a nested dictionary
people = {
"John": {
"age": 30,
"city": "New York"
},
"Jane": {
"age": 25,
"city": "Los Angeles"
}
}
# Accessing nested dictionary elements
print(f"John's age: {people['John']['age']}")
print(f"Jane's city: {people['Jane']['city']}")
Explanation:
people
: A dictionary containing two keys,"John"
and"Jane"
, where each key maps to another dictionary containing"age"
and"city"
.people['John']['age']
: This accesses the value of"age"
for the person"John"
.people['Jane']['city']
: This accesses the value of"city"
for the person"Jane"
.- Output:
John's age: 30
Jane's city: Los Angeles
6. Merging Two Dictionaries
Objective: Learn how to merge two dictionaries.
# Creating two dictionaries
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "job": "Engineer"}
# Merging dictionaries
merged_dict = {**dict1, **dict2}
print(f"Merged dictionary: {merged_dict}")
Explanation:
dict1 = {"name": "John", "age": 30}
: A dictionarydict1
is created.dict2 = {"city": "New York", "job": "Engineer"}
: Another dictionarydict2
is created.{**dict1, **dict2}
: The**
operator is used to unpack the dictionaries and merge them into a new dictionarymerged_dict
. If there are overlapping keys, values from the second dictionary (dict2
) will overwrite values from the first dictionary (dict1
).- Output:
Merged dictionary: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
7. Getting Keys, Values, and Items of a Dictionary
Objective: Learn how to retrieve keys, values, and items as separate views from a dictionary.
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Getting keys, values, and items
keys = person.keys()
values = person.values()
items = person.items()
print(f"Keys: {keys}")
print(f"Values: {values}")
print(f"Items: {items}")
Explanation:
person.keys()
: This returns a view of the keys in the dictionary.person.values()
: This returns a view of the values in the dictionary.person.items()
: This returns a view of the key-value pairs in the dictionary as tuples.- Output:
Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['John', 30, 'New York'])
Items: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
8. Default Values with get()
Method
Objective: Use the get()
method to safely access values and provide default values if a key does not exist.
# Creating a dictionary
person = {
"name": "John",
"age": 30
}
# Using the get() method with a default value
city = person.get("city", "Unknown")
print(f"City: {city}")
Explanation:
person.get("city", "Unknown")
: Theget()
method is used to retrieve the value associated with the"city"
key. If the key does not exist, it returns"Unknown"
as the default value.- Output:
City: Unknown
9. Dictionary Comprehension
Objective: Learn how to create dictionaries using dictionary comprehension.
# Creating a dictionary with comprehension
squared_numbers = {x: x**2 for x in range(1, 6)}
print(f"Squared numbers: {squared_numbers}")
Explanation:
{x: x**2 for x in range(1, 6)}
: This dictionary comprehension creates a dictionary where each key is a number from1
to5
, and the value is the square of the key.- Output:
Squared numbers: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Summary of Key Dictionary Operations:
- Dictionaries are mutable: You can add, update, or remove key-value pairs after creation.
- Accessing elements: Use square brackets
[]
to access values by key or theget()
method for safe access. - Iteration: You can iterate over keys, values, or key-value pairs using loops.
- Checking membership: Use the
in
operator to check if a key exists. - Nested dictionaries: Dictionaries can contain other dictionaries as values, enabling hierarchical data storage.
- Merging: Use the
**
operator to merge multiple dictionaries.
0 comments:
Post a Comment