In this tutorial, we will guide you through the process of creating a dictionary in Python. A dictionary in Python is an unordered collection of data that consists of key-value pairs. Each key-value pair in the dictionary maps the key to its associated value.
Step 1: Creating a Basic Dictionary
Firstly, to create a dictionary, you can use the curly braces {}
and place the key-value pairs inside the braces. The syntax is as follows: {key: value}.
Here is how you can create a simple dictionary in Python:
1 |
language_dictionary = {"name": "Python", "version": "3.9.1"} |
In this example, name
and version
are keys, and Python
and 3.9.1
are their values respectively.
Step 2: Accessing Values in a Dictionary
Once the dictionary is created, you can access the values using their keys like this:
1 2 |
print(language_dictionary["name"]) print(language_dictionary["version"]) |
Step 3: Adding a New Item to the Dictionary
To add a new item to the dictionary, you can simply specify the new key and its associated value. Here’s how:
1 |
language_dictionary["creator"] = "Guido van Rossum" |
Step 4: Updating a Dictionary
To update a dictionary, simply assign a new value to the key. Here is how:
1 |
language_dictionary["version"] = "3.9.2" |
Full Code:
1 2 3 4 5 6 7 8 |
language_dictionary = {"name": "Python", "version": "3.9.1"} print(language_dictionary["name"]) print(language_dictionary["version"]) language_dictionary["creator"] = "Guido van Rossum" language_dictionary["version"] = "3.9.2" |
Output:
Python 3.9.1
Conclusion
In conclusion, Python dictionaries are versatile and highly efficient. They are fundamental for many Python operations and algorithms. You can use dictionaries to store, retrieve, update and delete data. With the hands-on example in this tutorial, you should be able to confidently create, modify and access Python dictionaries in your projects.