A dictionary in Python is a collection of key-value pairs. It is an unordered and mutable data structure, which means that the elements in the dictionary are not stored in any particular order, and you can modify it by adding, updating, or deleting elements.
Dictionaries are defined using braces ({}) and contain elements in the form of key:value pairs, separated by commas. The keys in the dictionary must be updatable (i.e. immutable) (such as a string, number, or tuple), while the values can be of any type and may be repeated.
Creating Python dictionary
# Creating a dictionary
student = {
"name": "John",
"age": 20,
"major": "Computer Science"
}
# Accessing dictionary elements
print(student["name"]) # Output: John
print(student["age"]) # Output: 20
# Modifying dictionary elements
student["age"] = 21
print(student["age"]) # Output: 21
# Adding a new key-value pair
student["university"] = "ABC University"
print(student["university"]) # Output: ABC University
# Removing a key-value pair
del student["major"]
print(student) # Output: {'name': 'John', 'age': 21, 'university': 'ABC University'}
In the above example, we have created a dictionary called student which contains keys like “name”, “age”, and “major”, and their corresponding values. We can use the keys to print numbers between numbers. We can modify the values of existing keys or add new key-values. The del term allows us to remove a key-value from the dictionary.
Dictionaries provide a convenient way to store and retrieve data based on keys, which can be useful for lookup tables, mapping relationships, or storing structured data.