One of the most powerful features of Python is its easy manipulation of data structures. A dictionary, also known as an associative array in other languages, is a collection of key-value pairs where the key must be unique.
This tutorial is about creating dictionaries and adding key-value pairs to them dynamically in Python.
Step 1: How to Create a Dictionary
In Python, you can create a dictionary using the curly brackets {}
, and inside these brackets, keys and values are declared. Keep in mind that each key-value pair is separated by a colon :
. Different pairs are also separated by a comma ,
.
Here is a basic example:
1 2 |
my_dict = {} my_dict = {'name': 'John', 'age': 30, 'location': 'New York'} |
Step 2: Adding Elements
Adding elements to a dictionary is quite simple. You just need to use a new key and assign its value.
An example would be:
1 |
my_dict['job'] = 'Engineer' |
This will add a new key-value pair to the dictionary my_dict
with ‘job’ being the key and ‘Engineer’ the value.
Step 3: Adding Elements Dynamically
1 2 |
for i in range(1, 6): my_dict['key' + str(i)] = i |
After executing the above code, 5 new key-value pairs will be added to the dictionary my_dict
. The keys will be ‘key1’, ‘key2’, ‘key3’, ‘key4’, and ‘key5’. Each key’s value will be its corresponding integer.
Step 4: Displaying a Dictionary
To display a dictionary, you can simply print it using Python’s print function.
1 |
print(my_dict) |
The output will be:
1 |
{'name': 'John', 'age': 30, 'location': 'New York', 'job': 'Engineer', 'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5} |
The Full Code:
1 2 3 4 5 6 7 |
my_dict = {'name': 'John', 'age': 30, 'location': 'New York'} my_dict['job'] = 'Engineer' for i in range(1, 6): my_dict['key' + str(i)] = i print(my_dict) |
{'name': 'John', 'age': 30, 'location': 'New York', 'job': 'Engineer', 'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
Conclusion
Working with dictionaries is essential when dealing with data structure. This tutorial provided a simple way to create dictionaries and how to add key-value pairs to them dynamically.
Remember that dictionaries play a pivotal role in Python, and understanding them will make your programming journey easier. Always try to practice to get a solid grasp of the concept.