Dictionary Literals in Python
Dictionary literals are a concise way to create dictionaries in Python. They consist of a pair of curly braces {} enclosing a comma-separated list of key-value pairs.
Syntax:
Python
dictionary_name = {key1: value1, key2: value2, ...}
Example:
Python
person = {"name": "Alice", "age": 30, "city": "New York"}
Key Points:
- Keys must be unique within a dictionary.
- Values can be of any data type.
- Dictionary literals are immutable, meaning you cannot change the keys after creation.
Nested Dictionaries
You can create nested dictionaries by using dictionaries as values within other dictionaries:
Python
student_data = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
Empty Dictionaries
To create an empty dictionary, use empty curly braces:
Python
my_dict = {}