Dictionaries
Dictionaries in Python are data structures that store data in key-value pairs, allowing efficient data retrieval and modification based on unique keys.
What Is a Dictionary?
- Key-Value Pairs: Each entry in a dictionary consists of a key and its associated value.
- Access by Keys: Unlike lists, dictionaries are accessed via keys, not indices.
- Mutable: Dictionaries can be modified by adding, changing, or deleting elements.
- Key Types: Keys can be of various immutable data types like strings, integers, floats, and tuples.
- Value Types: Values can be of any data type, including lists and other dictionaries.
Creating an Empty Dictionary:
x = {}
print(type(x)) # Output: <class 'dict'>
Initializing Dictionaries
You can create a dictionary with initial key-value pairs:
file_counts = {
"jpg": 10,
"txt": 14,
"csv": 2,
"py": 23
}
print(file_counts)
Output:
{'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23}
Accessing Dictionary Values
-
By Key:
print(file_counts["txt"]) # Output: 14
-
Checking for a Key:
print("jpg" in file_counts) # Output: True
print("html" in file_counts) # Output: False
Modifying Dictionaries
-
Adding a New Key-Value Pair:
file_counts["cfg"] = 8
print(file_counts)Output:
{'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23, 'cfg': 8}
-
Updating an Existing Key's Value:
file_counts["csv"] = 17
print(file_counts)Output:
{'jpg': 10, 'txt': 14, 'csv': 17, 'py': 23, 'cfg': 8}
-
Deleting a Key-Value Pair:
del file_counts["cfg"]
print(file_counts)Output:
{'jpg': 10, 'txt': 14, 'csv': 17, 'py': 23}
Iterating Over Dictionaries
-
Iterating Over Keys:
for extension in file_counts:
print(extension)Output:
jpg
txt
csv
py -
Iterating Over Key-Value Pairs:
for ext, count in file_counts.items():
print(f"There are {count} files with the .{ext} extension")Output:
There are 10 files with the .jpg extension
There are 14 files with the .txt extension
There are 17 files with the .csv extension
There are 23 files with the .py extension -
Iterating Over Values:
for count in file_counts.values():
print(count)Output:
10
14
17
23
Counting Elements with Dictionaries
Dictionaries are ideal for counting the frequency of elements.
Example: Counting Letters in a String
def count_letters(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
Usage:
print(count_letters("tenant"))
Output:
{'t': 2, 'e': 1, 'n': 2, 'a': 1}
print(count_letters("a long string with a lot of letters"))
Output:
{'a': 2, ' ': 7, 'l': 3, 'o': 3, 'n': 2, 'g': 2, 's': 2, 't': 5, 'r': 2, 'i': 2, 'w': 1, 'h': 1, 'f': 1, 'e': 3}
Dictionaries vs. Lists
Similarities
- Collections: Both store collections of elements.
- Iteration: Both can be iterated over using loops.
- Mutability: Both are mutable; elements can be added, modified, or removed.
Differences
Feature | Dictionaries | Lists |
---|---|---|
Access Method | Via unique keys | Via index positions |
Order | Unordered (Python 3.7+ maintains insertion order) | Ordered |
Key Types | Immutable types (strings, integers, tuples, etc.) | Indices are integers starting from 0 |
Lookup Speed | Faster for large datasets (constant time complexity) | Slower as list size increases (linear time) |
Syntax | Curly braces {} with colons : between keys/values | Square brackets [] |
When to Use Dictionaries vs. Lists
- Use Dictionaries when:
- You need to associate values with unique keys.
- Fast lookup, insertion, and deletion are required.
- The dataset is large, and quick access is important.
- Use Lists when:
- You have an ordered collection of items.
- You need to access elements by their position.
- Order and sequence of elements are important.
Dictionary Methods and Operations
Common Operations
-
Get the Number of Items:
len(dictionary)
-
Access a Value by Key:
value = dictionary[key]
-
Set a Value by Key:
dictionary[key] = value
-
Delete a Key-Value Pair:
del dictionary[key]
Useful Methods
-
.get(key, default)
: Returns the value for a key if it exists, else returns a default value.value = dictionary.get(key, default_value)
-
.keys()
: Returns a view object of all keys.keys = dictionary.keys()
-
.values()
: Returns a view object of all values.values = dictionary.values()
-
.items()
: Returns a view object of all key-value pairs.items = dictionary.items()
-
Append to a List in a Dictionary:
dictionary[key].append(new_value)
-
Update with Another Dictionary:
dictionary.update(other_dictionary)
-
Clear All Items:
dictionary.clear()
-
Copy a Dictionary:
new_dict = dictionary.copy()
Practical Examples
Summing Values in a Dictionary
def sum_server_use_time(server):
total_use_time = 0.0
for user_time in server.values():
total_use_time += user_time
return round(total_use_time, 2)
file_server = {
"EndUser1": 2.25,
"EndUser2": 4.5,
"EndUser3": 1,
"EndUser4": 3.75,
"EndUser5": 0.6,
"EndUser6": 8
}
print(sum_server_use_time(file_server)) # Output: 20.1
Generating Full Names from a Dictionary
def list_full_names(employee_dictionary):
full_names = []
for last_name, first_names in employee_dictionary.items():
for first_name in first_names:
full_names.append(f"{first_name} {last_name}")
return full_names
print(list_full_names({
"Ali": ["Muhammad", "Amir", "Malik"],
"Devi": ["Ram", "Amaira"],
"Chen": ["Feng", "Li"]
}))
Output:
['Muhammad Ali', 'Amir Ali', 'Malik Ali', 'Ram Devi', 'Amaira Devi', 'Feng Chen', 'Li Chen']
Inverting a Dictionary
def invert_resource_dict(resource_dictionary):
inverted = {}
for resource_group, resources in resource_dictionary.items():
for resource in resources:
if resource in inverted:
inverted[resource].append(resource_group)
else:
inverted[resource] = [resource_group]
return inverted
resources = {
"Hard Drives": ["IDE HDDs", "SCSI HDDs"],
"PC Parts": ["IDE HDDs", "SCSI HDDs", "High-end video cards", "Basic video cards"],
"Video Cards": ["High-end video cards", "Basic video cards"]
}
print(invert_resource_dict(resources))
Output:
{
'IDE HDDs': ['Hard Drives', 'PC Parts'],
'SCSI HDDs': ['Hard Drives', 'PC Parts'],
'High-end video cards': ['PC Parts', 'Video Cards'],
'Basic video cards': ['PC Parts', 'Video Cards']
}
Resources
- Official Documentation:
- Tutorials:
- Additional Reading:
- Mapping Types — dict in the Python Standard Library documentation provides in-depth information about dictionary methods and operations.