In Python, a dictionary (often referred to as a dict
) is an unordered collection of items. Each item is stored as a key-value pair. Dictionaries are mutable, meaning you can change their contents after they are created. In this lesson, you'll learn about some common dictionary methods that you can use to manipulate and interact with them.
You can create a dictionary by enclosing key-value pairs inside curly braces {}
. The keys and values are separated by a colon :
.
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
fruits = {'apple': 3, 'banana': 2, 'cherry': 5}
You can access the value associated with a key using square brackets []
or the get()
method.
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person['name']) # Output: Alice
print(person.get('age')) # Output: 30
person['name']
accesses the value associated with the key 'name'
.person.get('age')
accesses the value associated with the key 'age'
.You can add or update a key-value pair by assigning a value to a key.
person['occupation'] = 'Engineer' # Adding a new key-value pair
person['age'] = 31 # Updating an existing key-value pair
print(person)
person['occupation'] = 'Engineer'
adds a new key 'occupation'
with the value 'Engineer'
.person['age'] = 31
updates the value of the existing key 'age'
to 31
.You can remove key-value pairs using the del
keyword or the pop()
method. The pop()
method also returns the value of the removed item.
del person['city'] # Removes the key 'city' and its associated value
removed_value = person.pop('age') # Removes the key 'age' and returns its value
print(person)
print('Removed value:', removed_value)
del person['city']
removes the key 'city'
and its associated value.removed_value = person.pop('age')
removes the key 'age'
and returns the removed value.Python provides several built-in methods to interact with dictionaries. Below are some common ones:
keys()
The keys()
method returns a view object that displays a list of all the keys in the dictionary.
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
keys = person.keys()
print(keys) # Output: dict_keys(['name', 'age', 'city'])
values()
The values()
method returns a view object that displays a list of all the values in the dictionary.
values = person.values()
print(values) # Output: dict_values(['Alice', 30, 'New York'])
items()
The items()
method returns a view object that displays a list of all the key-value pairs in the dictionary as tuples.
items = person.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
get()
The get()
method returns the value for the specified key. If the key does not exist, it returns None
(or a default value if provided).
name = person.get('name')
country = person.get('country', 'Not Found') # Returns 'Not Found' if 'country' key doesn't exist
print(name) # Output: Alice
print(country) # Output: Not Found
pop()
The pop()
method removes and returns the value of the specified key. If the key is not found, it raises a KeyError
.
removed_value = person.pop('city')
print(removed_value) # Output: New York
popitem()
The popitem()
method removes and returns the last key-value pair from the dictionary as a tuple. If the dictionary is empty, it raises a KeyError
.
last_item = person.popitem()
print(last_item) # Output: ('age', 30)
clear()
The clear()
method removes all key-value pairs from the dictionary.
person.clear()
print(person) # Output: {}
update()
The update()
method updates the dictionary with key-value pairs from another dictionary or iterable of key-value pairs.
person.update({'city': 'Los Angeles', 'age': 32})
print(person) # Output: {'name': 'Alice', 'age': 32, 'city': 'Los Angeles'}
You can create dictionaries using a concise syntax called dictionary comprehension.
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{x: x**2 for x in range(5)}
creates a dictionary with keys from 0 to 4, and values as the squares of the keys.
Objective: Practice using dictionary methods to manipulate and interact with dictionaries.
Create a Python File:
Create a file named dict_methods_practice.py
.
Add a Key-Value Pair: Add a key-value pair to a dictionary representing your contact information (name, phone number).
Example:
contact = {'name': 'Alice'}
contact['phone'] = '123-456-7890'
print(contact)
Update a Value: Update the value of an existing key in the dictionary.
Example:
contact['name'] = 'Bob'
print(contact)
Remove a Key-Value Pair:
Remove a key-value pair using del
or pop()
.
Example:
contact.pop('phone')
print(contact)
Get a Value:
Use the get()
method to retrieve a value for a key.
Example:
phone_number = contact.get('phone', 'Not Available')
print(phone_number)
Check Keys and Values:
Use keys()
and values()
to check the keys and values in a dictionary.
Example:
print(contact.keys())
print(contact.values())
Merge Dictionaries:
Merge two dictionaries using update()
.
Example:
address = {'city': 'New York', 'state': 'NY'}
contact.update(address)
print(contact)
Clear the Dictionary: Clear all key-value pairs in the dictionary.
Example:
contact.clear()
print(contact)