Dictionaries in python are built-in data type that stores a collection of key-value pairs. Each key is unique and associated with a value. Dictionaries are mutable, meaning you can modify their contents after creation. They are often used to represent structured data, where each piece of data is associated with a label or identifier (the key).

Creating a Dictionary: You can create a dictionary using curly braces {} and specifying key-value pairs separated by colons :. Here’s a basic example:

# Creating a dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

Accessing Values: You can access the values in a dictionary by referring to their corresponding keys:

# Accessing values
print(person["name"])  # Output: John
print(person["age"])   # Output: 30

Modifying Values: You can modify the value associated with a key:

# Modifying values
person["age"] = 31
print(person["age"])  # Output: 31

Adding New Key-Value Pairs: You can add new key-value pairs to a dictionary:

# Adding new key-value pairs
person["job"] = "Engineer"
print(person)
# Output: {'name': 'John', 'age': 31, 'city': 'New York', 'job': 'Engineer'}

Removing Key-Value Pairs: You can remove key-value pairs using the del statement:

# Removing a key-value pair
del person["city"]
print(person)
# Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}

Dictionary Methods and Functions: Dictionaries have various methods and functions for working with them. Here are a few examples:

# Getting keys and values
keys = person.keys()    # Returns a list of keys
values = person.values()  # Returns a list of values

# Checking if a key exists
if "age" in person:
    print("Age key exists")

# Clearing the dictionary
person.clear()  # Removes all key-value pairs from the dictionary

Practical Exercises:

Exercise 1: Create and Access Create a dictionary named student with keys "name", "age", and "grade". Assign appropriate values to each key. Print out the student’s name and grade.

Exercise 2: Modify and Add Modify the age of the student to one year older. Add a new key "school" with a value representing the student’s school name.

Exercise 3: Population Data Create a dictionary representing the population of three cities. Calculate and print the total population.

Exercise 4: Shopping List Create a shopping list dictionary with items as keys and quantities as values. Add, remove, and modify items in the shopping list.

Exercise 5: Phone Book Create a phone book dictionary with names as keys and phone numbers as values. Implement a function that takes a name as input and returns the corresponding phone number.

These exercises will give you practical experience in working with dictionaries in Python and understanding their usage in various contexts.

Leave a Reply

Your email address will not be published. Required fields are marked *