How to Create a Dictionary and Add Key-Value Pairs Dynamically in Python

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:

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:

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

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.

The output will be:

The Full Code:

{'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.