Python - Dictionaries
Think of dictionaries as real-world dictionaries, but instead of looking up word definitions, you're looking up values using unique keys.
Dictionaries are incredibly versatile and used extensively in Python to store and organize data in a structured and easily accessible way. They're like super-powered containers where each item has a specific label, making it quick to find what you need.
What is a Dictionary?
In Python, a dictionary is a collection of key-value pairs.
- A key is like the word you look up in a real dictionary. It must be unique within the dictionary and is often a string (text) or a number.
- A value is like the definition you find. It can be any Python data type – numbers, strings, lists, even other dictionaries!
These key-value pairs are enclosed in curly braces {} and each pair is separated by a colon : where the key comes before the value, and commas , separate the pairs.
Here's a simple example of a dictionary that stores the ages of some friends:
Python
ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35}
print(ages)
When you run this, you'll see:
{'Alice': 30, 'Bob': 25, 'Charlie': 35}
In this dictionary:
- 'Alice', 'Bob', and 'Charlie' are the keys.
- 30, 25, and 35 are the corresponding values.
You can think of it as a way to create direct associations between pieces of information. Instead of remembering that Alice is at a certain position in a list, you can directly ask the ages dictionary for the value associated with the key 'Alice'.
Examples
Ready to take the next step and see how to access information stored in a dictionary?
Great question! Dictionaries are useful in so many situations. Here are a couple of examples to illustrate how you might use them in your Python projects:
Example 1: Storing Information About a Student
Imagine you're building a program to manage student data. You could use a dictionary to store various pieces of information about a single student.
Python
student = {
'name': 'Maya Rodriguez',
'student_id': 'SR2023456',
'major': 'Computer Science',
'courses': ['Introduction to Programming', 'Calculus I', 'Linear Algebra'],
'grade_point_average': 3.85
}
print(student)
This dictionary student uses strings like 'name', 'student_id', 'major', 'courses', and 'grade_point_average' as keys. The corresponding values store the student's name (a string), ID (a string), major (a string), the list of courses they're taking (a list), and their GPA (a number).
Now, if you wanted to access a specific piece of information, you could use the key:
Python
print(f"Student Name: {student['name']}")
print(f"Student ID: {student['student_id']}")
print(f"Major: {student['major']}")
print(f"Courses Enrolled: {student['courses']}")
print(f"GPA: {student['grade_point_average']}")
This would output:
Student Name: Maya Rodriguez
Student ID: SR2023456
Major: Computer Science
Courses Enrolled: ['Introduction to Programming', 'Calculus I', 'Linear Algebra']
GPA: 3.85
See how easy it is to retrieve specific details using the descriptive keys?
Example 2: Counting Word Frequencies
Let's say you have a piece of text and you want to count how many times each word appears. A dictionary is perfect for this! The words can be the keys, and their counts can be the values.
Python
text = "the quick brown fox jumps over the lazy fox"
word_counts = {} # Create an empty dictionary to store the counts
words = text.split() # Split the text into a list of individual words
for word in words:
# If the word is already a key in the dictionary, increment its count
if word in word_counts:
word_counts[word] += 1
# If the word is not yet a key, add it to the dictionary with a count of 1
else:
word_counts[word] = 1
print(word_counts)
When you run this code, you'll get:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1}
Here, the dictionary word_counts tells you that the word 'the' appears 2 times, 'quick' appears 1 time, 'brown' appears 1 time, and so on. This is a common task in text analysis, and dictionaries make it very straightforward.
These two examples give you a glimpse of the power and flexibility of dictionaries in Python. They allow you to organize and access data in a meaningful way using keys. What would you like to explore next about Python dictionaries? Perhaps how to add, modify, or remove items?
Top 10 Functions
Excellent question! Just like Pandas has its go-to functions, Python dictionaries have their workhorse methods that you'll use frequently. Here are 10 of the most common and useful functions (or more accurately, methods since they are called on a dictionary object):
dict(): While not strictly a method called on an existing dictionary, dict() is the constructor used to create new dictionaries. You've already seen the literal notation with curly braces {}, but dict() offers other ways to build dictionaries, such as from a list of key-value pairs or keyword arguments.
Python
# Creating a dictionary using dict() with key-value pairs
data1 = dict([('apple', 1), ('banana', 2)])
print(data1) # Output: {'apple': 1, 'banana': 2}
# Creating a dictionary using dict() with keyword arguments
data2 = dict(name='Alice', age=30)
print(data2) # Output: {'name': 'Alice', 'age': 30}
keys(): This method returns a view object that displays a list of all the keys in the dictionary. It's often used to iterate over the keys.
Python
student = {'name': 'Bob', 'major': 'Physics', 'grade': 'A'}
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'major', 'grade'])
for key in student.keys():
print(key)
values(): Similar to keys(), this method returns a view object that displays a list of all the values in the dictionary. You can use it to access all the values.
Python
student = {'name': 'Bob', 'major': 'Physics', 'grade': 'A'}
values = student.values()
print(values) # Output: dict_values(['Bob', 'Physics', 'A'])
for value in student.values():
print(value)
items(): This method returns a view object that displays a list of all the key-value pairs in the dictionary as tuples. This is very useful for iterating over both keys and values simultaneously.
Python
student = {'name': 'Bob', 'major': 'Physics', 'grade': 'A'}
items = student.items()
print(items) # Output: dict_items([('name', 'Bob'), ('major', 'Physics'), ('grade', 'A')])
for key, value in student.items():
print(f"{key}: {value}")
get(key, default): This method returns the value for a given key. If the key is not in the dictionary, it returns the default value (if provided) or None. This is a safer way to access values than using square brackets [] because it avoids a KeyError if the key doesn't exist.
Python
student = {'name': 'Bob', 'major': 'Physics'}
name = student.get('name')
print(name) # Output: Bob
age = student.get('age')
print(age) # Output: None
age_with_default = student.get('age', 20)
print(age_with_default) # Output: 20
update(other_dictionary): This method updates the dictionary with the key-value pairs from another dictionary or from an iterable of key-value pairs. If a key already exists,1 its value is updated; otherwise, new key-value pairs are added.
Python
student = {'name': 'Bob', 'major': 'Physics'}
additional_info = {'age': 20, 'city': 'Northampton'}
student.update(additional_info)
print(student) # Output: {'name': 'Bob', 'major': 'Physics', 'age': 20, 'city': 'Northampton'}
more_info = [('grade', 'A+'), ('advisor', 'Dr. Smith')]
student.update(more_info)
print(student) # Output: {'name': 'Bob', 'major': 'Physics', 'age': 20, 'city': 'Northampton', 'grade': 'A+', 'advisor': 'Dr. Smith'}
pop(key, default): This method removes the item with the specified key and returns its value. If the key is not found, it raises a KeyError unless a default value is provided, in which case it returns the default value.
Python
student = {'name': 'Bob', 'major': 'Physics', 'age': 20}
age = student.pop('age')
print(f"Popped age: {age}") # Output: Popped age: 20
print(student) # Output: {'name': 'Bob', 'major': 'Physics'}
# Trying to pop a non-existent key without a default will raise an error
# grade = student.pop('grade') # This would cause a KeyError
grade = student.pop('grade', 'Not Available')
print(f"Popped grade: {grade}") # Output: Popped grade: Not Available
print(student) # Output: {'name': 'Bob', 'major': 'Physics'}
popitem(): This method removes and returns the last inserted key-value pair from the dictionary as a tuple. In Python versions before 3.7, the order of items in a dictionary was not guaranteed, so popitem() would remove an arbitrary item. However, in Python 3.7 and later, dictionaries remember the insertion order.
Python
student = {'name': 'Bob', 'major': 'Physics', 'grade': 'A'}
last_item = student.popitem()
print(f"Popped item: {last_item}") # Output: ('grade', 'A')
print(student) # Output: {'name': 'Bob', 'major': 'Physics'}
clear(): This method removes all items from the dictionary, making it empty.
Python
student = {'name': 'Bob', 'major': 'Physics'}
student.clear()
print(student) # Output: {}
copy(): This method returns a shallow copy of the dictionary. A shallow copy means that a new dictionary object is created, but if the original dictionary contains mutable objects (like lists), the copy will still refer to the same inner objects.
Python
student = {'name': 'Bob', 'courses': ['Physics 101', 'Math 201']}
student_copy = student.copy()
print(f"Original student: {student}") # Output: {'name': 'Bob', 'courses': ['Physics 101', 'Math 201']}
print(f"Copied student: {student_copy}") # Output: {'name': 'Bob', 'courses': ['Physics 101', 'Math 201']}
# Modifying the list in the original also affects the copy (shallow copy)
student['courses'].append('Chemistry 101')
print(f"Original student after modification: {student}") # Output: {'name': 'Bob', 'courses': ['Physics 101', 'Math 201', 'Chemistry 101']}
print(f"Copied student after original's modification: {student_copy}") # Output: {'name': 'Bob', 'courses': ['Physics 101', 'Math 201', 'Chemistry 101']}
These ten methods will cover the vast majority of your interactions with Python dictionaries. Understanding how to use them effectively will make your Python code cleaner, more efficient, and easier to manage. What would you like to delve into next regarding dictionaries? Perhaps how they differ from lists or tuples?