Key Concepts of a dict
A dictionary in Python contains a collection of key:value pairs.
Keys must be unique and are typically immutable, such as strings, numbers, or tuples.
Values can be of any type, and they can be duplicated.
Creating a Dictionary
Literal Definition: Define key-value pairs within curly braces { }.
zip() example
keys = ["a", "b", "c"]
values = [1, 2, 3]
zipped = zip(keys, values)
dict_from_zip = dict(zipped) # Result: {"a": 1, "b": 2, "c": 3}Key-Value Pairs example
# Using the `dict()` constructor
student_dict = dict([
("name", "John Doe"),
("age", 21),
("courses", ["Math", "Physics"])
])
Using the shorthand syntax
student_dict_short = {
"name": "John Doe",
"age": 21,
"courses": ["Math", "Physics"]
}dict() Constructor example
# Sequence of key-value pairs student_dict2 = dict(name="Jane Doe", age=22, courses=["Biology", "Chemistry"]) From another dictionary student_dict_combined = dict(student, **student_dict2)