Understanding Python Dictionaries
Python dictionaries are unordered collections of items. Each item is a key-value pair. Dictionaries are mutable, which means they can be changed after creation. They are defined using curly braces {}
with key-value pairs separated by colons.
Creating Dictionaries
Example 1: Creating a Dictionary
# Creating a dictionary
person = {
"name": "Karthick AG",
"age": 30,
"city": "Chennai"
}
print("Person Dictionary:", person)
Output
Person Dictionary: {'name': 'Karthick AG', 'age': 30, 'city': 'Chennai'}
Example 2: Using the dict()
Constructor
# Creating a dictionary using dict()
person = dict(name="Durai", age=28, city="Coimbatore")
print("Person Dictionary:", person)
Person Dictionary: {'name': 'Durai', 'age': 28, 'city': 'Coimbatore'}
Example 3: Creating an Empty Dictionary
# Creating an empty dictionary
empty_dict = {}
print("Empty Dictionary:", empty_dict)
Empty Dictionary: {}
Explanation: Dictionaries are created using curly braces with key-value pairs. Keys must be unique and immutable types such as strings, numbers, or tuples. Values can be of any data type.