A Few Words on Dictionaries
Dictionaries are one of the most widely-used data structures in Python. They are an unordered collection of key-value pairs where each key is unique and must be hashable (i.e., immutable).
Values in dictionaries can be of any datatype, but keys must be a hashable type such as strings, tuples, and numbers. Dictionaries are also mutable, meaning that you can add, remove, and update key-value pairs.
Python first introduced dictionaries in version 1.0. The implementation of dictionaries has changed over the years in terms of ordering. In Python 2.x, the order of key-value pairs was arbitrary.
However, in Python 3.x, dictionaries maintain the order of insertion. In Python 3.7, dictionaries also have some support for randomized data structures, such as randomization of hash functions, adding a new dimension to the implementation of dictionaries.
How to Iterate Through a Dictionary in Python: The Basics
Iterating Through Keys Directly
One of the easiest ways to iterate through a dictionary is by iterating through its keys directly. This can be done with a simple `for` loop as shown below:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in
my_dict:
print(key)
“`
This would output:
“`
a
b
c
“`
You can also use the indexing operator to access values in the dictionary:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in
my_dict:
print(f”{key}: {
my_dict[key]}”)
“`
This would output:
“`
a: 1
b: 2
c: 3
“`
Iterating Through `.items()`
Another way to iterate through a dictionary is by using the `.items()` method. This method returns a tuple containing the key-value pair for each element in the dictionary.
You can then use tuple unpacking to assign each key-value pair to separate variables:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key, value in
my_dict.items():
print(f”{key}: {value}”)
“`
This would output:
“`
a: 1
b: 2
c: 3
“`
This approach is more efficient as it doesn’t require accessing the dictionary for each iteration. Iterating Through `.keys()`
If you only need to iterate through the keys in a dictionary, you can use the `.keys()` method:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in
my_dict.keys():
print(key)
“`
This would output:
“`
a
b
c
“`
Iterating Through `.values()`
Similarly, if you only need to iterate through the values in a dictionary, you can use the `.values()` method:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for value in
my_dict.values():
print(value)
“`
This would output:
“`
1
2
3
“`
One advantage of using `.values()` is that it allows you to use membership tests to determine if a specific value is in the dictionary. In conclusion, dictionaries are powerful data structures in Python that allow you to store key-value pairs.
You can iterate through dictionaries by iterating through keys directly, using the `.items()` method, or using the `.keys()` and `.values()` methods. Each of these methods has its advantages depending on what you are trying to accomplish.
With this knowledge, you can better leverage dictionaries to store, manipulate and analyze data in your Python programs.
Modifying Values and Keys
Dictionaries as a data structure are designed to be quite fluid. This means that it is easy to modify values and keys in a dictionary quickly.
Let’s explore the different ways on how to do this.
Modifying Values of a Dictionary
The easiest way to modify a value of a dictionary is by directly assigning a value to a key. For example:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
my_dict[‘b’] = 4
“`
After executing this code block, `
my_dict` will be `{‘a’: 1, ‘b’: 4, ‘c’: 3}`. In this example, we modified the value of the key `b` from `2` to `4`.
Another way to modify values is to iterate through the dictionary and change values explicitly. Here’s an example of how to double every value in a given dictionary:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in
my_dict:
my_dict[key] *= 2
“`
After executing this code block, `
my_dict` will become `{‘a’: 2, ‘b’: 4, ‘c’: 6}`. Here, we used a `for` loop to iterate through the keys of the dictionary and modify their corresponding values.
Modifying Keys of a Dictionary
In order to modify a key in a dictionary, we must first create a new key-value pair with the desired key and value, and then delete the old key-value pair. Here’s an example:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
my_dict[‘new_key’] =
my_dict.pop(‘b’)
“`
After executing this code block, `
my_dict` will become `{‘a’: 1, ‘c’: 3, ‘new_key’: 2}`. Here, we created a new key-value pair with the key `new_key` and the value of the old key `b`, and then deleted the old key-value pair.
We can also modify keys by iterating through the dictionary and removing the old key-value pairs and adding new ones. Here’s an example of how to update keys in a dictionary:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
new_dict = {}
for key, value in
my_dict.items():
if key == ‘b’:
new_dict[‘new_key’] = value
else:
new_dict[key] = value
my_dict = new_dict
“`
After executing this code block, `
my_dict` will become `{‘a’: 1, ‘c’: 3, ‘new_key’: 2}`. Here, we created a new dictionary `new_dict` and iterated through the old dictionary, adding key-value pairs to the new dictionary and modifying the keys.
Real-World Examples
Turning Keys Into Values and Vice Versa
One real-world example of modifying dictionary keys and values is when you need to switch them. For instance, assume you have a dictionary with names as keys, and corresponding ages as values.
You may then need to switch these to be organized by age:
“`python
my_dict = {‘Alice’: 23, ‘Bob’: 29, ‘Charlie’: 32, ‘David’: 26}
new_dict = {age: name for name, age in
my_dict.items()}
“`
After executing this code block, `new_dict` will become `{23: ‘Alice’, 29: ‘Bob’, 32: ‘Charlie’, 26: ‘David’}`.
Doing Some Calculations
In some situations, you may need to perform calculations using the values in a dictionary. For example, suppose you have a dictionary containing sales information for a business over time:
“`python
sales = {
‘Q1’: 10_000,
‘Q2’: 25_000,
‘Q3’: 15_000,
‘Q4’: 20_000
}
“`
You might want to calculate the total sales over the entire year.
Here’s how you can do that:
“`python
total_sales = sum(sales.values())
“`
After executing this code block, `total_sales` will become `70_000`.
Using Comprehensions
Dictionary comprehensions provide a concise way to modify a dictionary by iterating through its keys and values and creating a new dictionary based on a particular condition. Here’s an example of how to filter out certain elements from a dictionary using a comprehension:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
filtered_dict = {k: v for k, v in
my_dict.items() if k != ‘c’}
“`
After executing this code block, `filtered_dict` will become `{‘a’: 1, ‘b’: 2, ‘d’: 4}`. Here, we used a comprehension to create a new dictionary `filtered_dict`, with only key-value pairs whose keys are not equal to `’c’`.
In conclusion, modifying keys and values in a dictionary is a simple task in Python. You can modify values by directly assigning a new value to a key, iterating through the dictionary and modifying each value, or using a comprehension.
Modifying keys requires creating a new key-value pair and deleting the old one or iterating through the dictionary and replacing old keys with new ones. With these techniques, you can manipulate and transform dictionaries to fit your needs.
Removing Specific Items
Sometimes, you need to remove specific items from a dictionary. You can use different methods to remove a specific item from a dictionary, such as using `del`, `.pop()`, or iterating through the dictionary.
If you know the key of the item you want to remove, you can use `del` to delete that key-value pair:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
del
my_dict[‘b’]
“`
After executing this code block, `
my_dict` will become `{‘a’: 1, ‘c’: 3}`. `.pop()` is another way to remove specific items by their key:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
removed_value =
my_dict.pop(‘b’)
“`
After executing this code block, `
my_dict` will become `{‘a’: 1, ‘c’: 3}` and `removed_value` will become `2`. If you don’t know the keys of the items you want to remove, you can iterate through the dictionary and remove the items that meet a specific condition:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
to_remove = []
for key, value in
my_dict.items():
if value > 2:
to_remove.append(key)
for key in to_remove:
del
my_dict[key]
“`
After executing this code block, `
my_dict` will become `{‘a’: 1, ‘b’: 2}`. Here, we first create a list of keys of items with values greater than 2.
We then remove each item with a key in that list.
Sorting a Dictionary
Python dictionaries are unordered by nature. However, there are instances in which we may want to sort a dictionary by key or value.
Let’s explore some methods to sort a dictionary in Python.
Iterating in Sorted Order
One way to sort a dictionary is to iterate through it in sorted order using the `sorted()` function. This will only sort the keys:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
for key in sorted(
my_dict):
print(key,
my_dict[key])
“`
This will output:
“`
a 1
b 2
c 3
“`
Note that `sorted()` doesn’t modify the dictionary; it just sorts the result when you iterate through it.
Sorted by Keys
The `.sort()` method can be used to sort the dictionary by keys. Here’s an example:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
sorted_dict = {}
for key in sorted(
my_dict.keys()):
sorted_dict[key] =
my_dict[key]
“`
After executing this code block, `sorted_dict` will become `{‘a’: 1, ‘b’: 2, ‘c’: 3}`. Here, we sorted the keys using `sorted()` and created a new dictionary with the sorted keys.
You could also use a dictionary comprehension to accomplish the same thing:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
sorted_dict = {k:
my_dict[k] for k in sorted(
my_dict.keys())}
“`
This approach is more concise and creates the sorted dictionary in one line.
Sorted by Values
In situations where you want to sort a dictionary by its values, you can use the `sorted()` function and a `lambda` function as the key parameter:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
sorted_dict = {}
for key, value in sorted(
my_dict.items(), key=lambda x: x[1]):
sorted_dict[key] = value
“`
After executing this code block, `sorted_dict` will become `{‘a’: 1, ‘b’: 2, ‘c’: 3}`. Here, we used a `lambda` function to return the second (value) element in each item tuple when sorting the dictionary items.
This approach can also be accomplished via dictionary comprehension:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
sorted_dict = {k: v for k, v in sorted(
my_dict.items(), key=lambda x: x[1])}
“`
This approach is more concise and accomplishes the same thing in a single line of code.
Reversed
In some instances, you may want to iterate over a dictionary in reverse order. To achieve this, you can use the `reversed()` function:
“`python
my_dict = {‘b’: 2, ‘c’: 3, ‘a’: 1}
for key in reversed(sorted(
my_dict)):
print(key,
my_dict[key])
“`
This will output:
“`
c 3
b 2
a 1
“`
In conclusion, Python provides various methods to sort a dictionary based on the key or value. You can sort a dictionary by iterating through the sorted keys, sorting by keys using `.sort()` or dictionary comprehension, sorting by values using a `lambda` function with the `sorted()` function, or reversing the dictionary order using `reversed()`.
With these techniques, you can manipulate and sort dictionaries to fit your needs. Iterating Destructively With `.popitem()`
The `.popitem()` method is another way to iterate through a dictionary, destructively.
This means that the method’s result will affect the original dictionary. `.popitem()` removes and returns an arbitrary item (key-value pair) from the dictionary as a tuple.
Here’s an example:
“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
while
my_dict:
key, value =
my_dict.popitem()
print(f”{key}: {value}”)
“`
This will output:
“`
c: 3
b: 2
a: 1
“`
In this example, we iterate through the dictionary using a `while` loop and destructively remove each item using `.popitem()`. We assign the returned key and value to variables `key` and `value` and print them to the console.
Using Some of Python’s Built-In Functions
Python has a collection of built-in functions that are useful when working with dictionaries. Using `map()`
`map()` is a built-in Python function that takes a function and an iterable as arguments and applies the function to each item in the iterable.
You can use `map()` to apply a function to all elements in a dictionary. Here’s an example:
“`python