Welcome to our comprehensive guide on Python Dictionaries! In this lesson, we'll learn about this powerful data structure, understand why they are essential, and explore their use in practical scenarios. Let's dive in!
A dictionary in Python is a collection of key-value pairs. Think of it as a box where each item (value) is labeled with a specific name (key).
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}In the example above, 'name', 'age', and 'city' are keys, and 'John', 30, and 'New York' are their corresponding values.
Dictionaries are useful because they allow us to store and access data quickly. Unlike lists, dictionaries can look up values using keys, making them ideal for efficient data retrieval.
Creating a dictionary is as simple as assigning a new set of key-value pairs to a variable.
# Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Accessing values
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30
print(my_dict['city']) # Output: New YorkYou can add new key-value pairs to an existing dictionary using the [] operator.
# Adding a new key-value pair
my_dict['job'] = 'Developer'
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Developer'}You can modify the value of an existing key by reassigning it.
# Modifying an existing value
my_dict['age'] = 35
print(my_dict)
# Output: {'name': 'John', 'age': 35, 'city': 'New York', 'job': 'Developer'}To check if a key exists in a dictionary, you can use the in keyword.
# Checking if a key exists
if 'job' in my_dict:
print('The key "job" exists.')
# Output: The key "job" exists.To remove a key-value pair, you can use the del keyword or the pop() method.
# Removing a key-value pair using del
del my_dict['city']
print(my_dict)
# Output: {'name': 'John', 'age': 35, 'job': 'Developer'}
# Removing a key-value pair using pop()
my_city = my_dict.pop('city')
print(my_dict)
# Output: {'name': 'John', 'age': 35, 'job': 'Developer'}
print(my_city) # Output: New YorkTo copy a dictionary, you can use the copy() method or the dict() function.
# Copying a dictionary using copy()
my_dict_copy = my_dict.copy()
print(my_dict_copy)
# Output: {'name': 'John', 'age': 35, 'job': 'Developer'}
# Copying a dictionary using dict()
my_dict_copy_2 = dict(my_dict)
print(my_dict_copy_2)
# Output: {'name': 'John', 'age': 35, 'job': 'Developer'}You can loop through dictionaries using the for loop.
# Looping through a dictionary
for key, value in my_dict.items():
print(f'Key: {key}, Value: {value}')
# Output:
# Key: name, Value: John
# Key: age, Value: 35
# Key: job, Value: DeveloperWhat does a dictionary in Python store?
By the end of this lesson, you should have a solid understanding of Python Dictionaries. Now, let's put our knowledge into practice by building a simple address book application! Stay tuned for the next lesson. 🎯