Adding keys and values to a dictionary is a common operation when working with Python. It allows you to store and retrieve data in an organized and efficient manner. In this tutorial, we will go over how to use a for loop to add keys and values to a dictionary in Python.
Steps:
1. Create an empty dictionary using curly braces {} or the built-in dict() function.
1 2 3 |
my_dict = {} # or my_dict = dict() |
2. Create a for loop that iterates over a sequence of values. In this example, we will use a list of numbers.
1 2 3 |
numbers = [1, 2, 3, 4, 5] for num in numbers: # add key-value pairs to dictionary here |
3. Within the for loop, use square brackets [] to add keys and assign values to the dictionary. In this example, we will use each number in the list as a key and its square as the value.
1 2 3 4 |
numbers = [1, 2, 3, 4, 5] my_dict = {} for num in numbers: my_dict[num] = num*num |
4. Print the resulting dictionary to confirm that the keys and values have been added correctly.
1 2 3 4 5 6 7 |
numbers = [1, 2, 3, 4, 5] my_dict = {} for num in numbers: my_dict[num] = num*num print(my_dict) |
Output:
{ 1: 1, 2: 4, 3: 9, 4: 16, 5: 25 }
Conclusion
Adding keys and values to a dictionary in Python is a simple and powerful way to manage your data.
Using a for loop to add multiple keys and values at once can save you time and help keep your code organized. Experiment with different data types and loops to create custom dictionaries for your projects.