A Python dictionary is a collection of key-value pairs
. It is one of Python's built-in
data types, and it is highly useful for storing and organizing data.
Dictionary Properties
- Unordered: Dictionaries
do not maintain the order of items
. However, starting fromPython 3.7
, dictionaries maintain theinsertion order
as an implementation detail i.ethey are ordered now
. InPython 3.8 and later, this behavior is officially guaranteed
. - Mutable: Dictionaries are
mutable
, meaning that you canchange, add, or remove items
after the dictionary has been created. - Indexed by keys: Each item in a dictionary is
accessed via a unique key
. Keys must be immutable types, like strings, numbers, or tuples with immutable elements, while the values can be of any type. - Unique keys: Keys within a dictionary must be unique. If you use the same key multiple times, the last assignment will overwrite the previous one.
Example to show these properties:
Creating Dict -
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } print(student)
Accessing elements in dict
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } # Accessing values print(student["name"]) # Output: John Doe print(student["courses"]) # Output: ['Math', 'Science']
Adding New element to dict
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } # Adding a new key-value pair student["GPA"] = 3.8 print(student)
Modify existing key in dict
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } # Modifying an existing key-value pair student["age"] = 21 print(student)
Check if key exists in dict
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } # Checking if a key exists print("name" in student) # Output: True print("graduated" in student) # Output: False
Iterating over in dict
# Creating a dictionary student = { "name": "John Doe", "age": 20, "courses": ["Math", "Science"], "graduated": False } # Iterating over keys and values for key, value in student.items(): print(f"{key}: {value}") # Output: # name: John Doe # age: 21 # courses: ['Math', 'Science'] # GPA: 3.8
Here -