Dictionary
or dict() in Python
is a built-in data structure that allows us to store key-value pairs. This data structure is mutable
meaning that we can modify
add
or delete key-value pairs as needed. In this article
we will discuss the basics of dictionaries
how to use them in Python
and some common operations you can perform with dictionaries.
To create a dictionary in Python
you can use curly braces { } and separate each key-value pair with a colon :. For example:
my_dict = { "name": "John"
"age": 30
"city": "New York" }
In the above example
we have created a dictionary with three key-value pairs: "name" is the key and "John" is the corresponding value
"age" is the key and 30 is the corresponding value
and "city" is the key and "New York" is the corresponding value.
You can access the values in a dictionary by using the keys. For example
to access the value associated with the key "name" in the dictionary above
you can do:
print(my_dict["name"])
This will output "John"
as that is the value associated with the key "name" in the dictionary.
You can also update the value of a key in a dictionary by assigning a new value to that key. For example
to update the age in the dictionary above
you can do:
my_dict["age"] = 35
Now
the value associated with the key "age" in the dictionary will be 35 instead of 30.
You can also add new key-value pairs to a dictionary by simply assigning a value to a new key. For example
to add a new key "gender" with the value "male" to the dictionary above
you can do:
my_dict["gender"] = "male"
Now
the dictionary will have a new key "gender" with the value "male".
To delete a key-value pair from a dictionary
you can use the del keyword followed by the key. For example
to delete the key "city" and its corresponding value from the dictionary above
you can do:
del my_dict["city"]
Now
the dictionary will no longer have the key "city" and its value.
You can also check if a key exists in a dictionary using the in keyword. For example
to check if the key "city" exists in the dictionary above
you can do:
if "city" in my_dict:
print("City exists in the dictionary")
else:
print("City does not exist in the dictionary")
Dictionaries are a powerful data structure in Python that allows us to store and manipulate key-value pairs efficiently. They are commonly used in various programming tasks
such as database operations
configuration settings
and more. They are also widely used in web development
data analysis
and machine learning applications.
In conclusion
dictionaries in Python are a versatile and powerful data structure that allows us to store and manipulate key-value pairs. By understanding the basics of dictionaries and how to use them in Python
you can make your code more efficient and effective. We hope this article has been helpful in explaining the concept of dictionaries and how to work with them in Python.