Working with Dictionaries in Python
Dictionaries are a versatile and powerful data structure in Python, often used to store data in key-value pairs. Unlike sequences like lists and tuples, dictionaries provide a fast way to retrieve values based on a unique key. This module will cover the basics of working with dictionaries, their operations, methods, and advanced use cases.
Subtopic 1: Introduction to Dictionaries
A dictionary in Python is an unordered collection of items, where each item is a key-value pair. Keys must be unique and immutable (strings, numbers, or tuples), while values can be any data type.
Creating a Dictionary
A dictionary is created by placing key-value pairs inside curly braces {}, with each key and value separated by a colon :.
my_dict = {'name': 'John', 'age': 25, 'location': 'New York'}
print(my_dict) # Output: {'name': 'John', 'age': 25, 'location': 'New York'}
You can also create an empty dictionary and add key-value pairs dynamically:
empty_dict = {}
empty_dict['name'] = 'Alice'
empty_dict['age'] = 30
print(empty_dict) # Output: {'name': 'Alice', 'age': 30}
Subtopic 2: Dictionary Operations
Python dictionaries support various operations for querying and modifying data.
Accessing Values by Key
You can access the value associated with a key using square brackets []. If the key is not present, a KeyError will be raised.
my_dict = {'name': 'John', 'age': 25}
print(my_dict['name']) # Output: John
To avoid KeyError, you can use the get() method, which returns None if the key is not found:
print(my_dict.get('location')) # Output: None
Adding or Updating Key-Value Pairs
You can add a new key-value pair or update the value of an existing key by directly assigning a value to the key.
my_dict['location'] = 'New York' # Adds a new key-value pair
my_dict['age'] = 26 # Updates the value of 'age'
print(my_dict) # Output: {'name': 'John', 'age': 26, 'location': 'New York'}
Removing Key-Value Pairs
You can remove items from a dictionary using the del statement or the pop() method.
del my_dict['location'] # Removes the key 'location'
print(my_dict) # Output: {'name': 'John', 'age': 26}
removed_value = my_dict.pop('age') # Removes 'age' and returns its value
print(removed_value) # Output: 26
print(my_dict) # Output: {'name': 'John'}
Checking for Existence of a Key
You can check whether a key exists in the dictionary using the in keyword.
print('name' in my_dict) # Output: True
print('location' in my_dict) # Output: False
Length of Dictionary
Use len() to get the number of key-value pairs in the dictionary.
print(len(my_dict)) # Output: 1
Subtopic 3: Dictionary Methods
Python dictionaries come with several built-in methods for manipulating data. Here are some commonly used ones:
-
clear(): Removes all items from the dictionary.my_dict.clear() print(my_dict) # Output: {} -
copy(): Returns a shallow copy of the dictionary.new_dict = my_dict.copy() print(new_dict) # Output: {'name': 'John', 'age': 25} -
fromkeys(): Creates a new dictionary from a sequence of keys, each with a specified value (default isNone).keys = ['a', 'b', 'c'] new_dict = dict.fromkeys(keys, 0) print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0} -
get(): Returns the value for the given key, or a default value (None if the key is not found).print(my_dict.get('name')) # Output: 'John' print(my_dict.get('address', 'Unknown')) # Output: 'Unknown' -
items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.items = my_dict.items() print(items) # Output: dict_items([('name', 'John'), ('age', 25)]) -
keys(): Returns a view object that displays a list of all the keys in the dictionary.keys = my_dict.keys() print(keys) # Output: dict_keys(['name', 'age']) -
pop(): Removes and returns the value for the specified key.age = my_dict.pop('age') print(age) # Output: 25 print(my_dict) # Output: {'name': 'John'} -
popitem(): Removes and returns an arbitrary (key, value) pair from the dictionary.item = my_dict.popitem() print(item) # Output: ('name', 'John') print(my_dict) # Output: {} -
setdefault(): Returns the value of the key if it exists, otherwise inserts the key with a specified default value.print(my_dict.setdefault('name', 'Default')) # Output: 'Default' print(my_dict) # Output: {'name': 'Default'} -
update(): Updates the dictionary with the elements from another dictionary or an iterable of key-value pairs.my_dict.update({'age': 26, 'location': 'New York'}) print(my_dict) # Output: {'name': 'John', 'age': 26, 'location': 'New York'} -
values(): Returns a view object that displays a list of all the values in the dictionary.values = my_dict.values() print(values) # Output: dict_values(['John', 26, 'New York'])
Subtopic 4: Using Dictionaries as Key-Value Stores
Dictionaries are ideal for situations where you need to map keys to values, such as in a simple key-value store or when storing metadata. You can use dictionaries to simulate the behavior of databases or caches, especially in smaller applications or scenarios where speed is important.
Example: Counting Frequency of Words in a String
You can use a dictionary to count the occurrence of each word in a string, which is a common task in text analysis.
sentence = "this is a test this is only a test"
word_counts = {}
for word in sentence.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
# Output: {'this': 2, 'is': 2, 'a': 2, 'test': 2, 'only': 1}
Example: Storing Student Grades
You can store student grades as key-value pairs, where the key is the student's name and the value is their grade.
student_grades = {'Alice': 85, 'Bob': 90, 'Charlie': 78}
print(student_grades['Bob']) # Output: 90
Example: Simulating a Cache System
Dictionaries are often used to store data temporarily to speed up repeated queries, simulating a cache system.
cache = {}
def get_data_from_cache(query):
if query in cache:
return cache[query]
else:
data = fetch_data_from_database(query)
cache[query] = data
return data