How to create a dictionary in Python?
Creating a dictionary in Python is straightforward. A dictionary is a collection of key-value pairs, where each key is unique. To create a dictionary, you use curly braces {}
and separate keys and values with a colon :
. Here's a basic example:
# Creating an empty dictionary
my_dict = {}
# Creating a dictionary with initial key-value pairs
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
In this example, the dictionary my_dict
has three key-value pairs. The key "name"
has the value "Alice"
, the key "age"
has the value 25
, and the key "city"
has the value "New York"
. You can access the values in a dictionary using their keys:
print(my_dict["name"]) # Output: Alice
print(my_dict["age"]) # Output: 25
You can also add or update key-value pairs in a dictionary:
my_dict["email"] = "alice@example.com" # Adds a new key-value pair
my_dict["age"] = 26 # Updates the value of the existing key
To remove a key-value pair, you can use the del
statement:
del my_dict["city"]
Dictionaries are highly versatile and can store various data types as values, including lists and other dictionaries. They are widely used for tasks like data retrieval, manipulation, and more. For a comprehensive understanding and hands-on practice, consider enrolling in a python certification course.
Visit on:- https://www.theiotacademy.co/python-training