Key-Value Pairs
-
This lesson explains how dictionaries store data in key-value format in Python.
What is a Dictionary?
A dictionary in Python is a data type used to store data in key–value pairs.
Each key is like a label
Each value is the data related to that key
Think like a real dictionary:
Word (Key) → Meaning (Value)Syntax to Create a Dictionary
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Rules of Dictionary
Keys must be unique
Keys are usually strings, numbers, or tuples
Values can be any data type
Dictionaries are written using curly braces { }
Student Dictionary
Stores student information using key–value pairs.
student = {
"name": "Amit",
"age": 20,
"course": "Python"
}
print(student)
Product Details Dictionary
This dictionary stores product details like name, price, and stock.
product = {
"product_name": "Laptop",
"price": 45000,
"stock": 10
}
print(product)
Dictionary with Different Data Types
Shows that dictionary values can be of different types.
data = {
"name": "Riya",
"marks": 85,
"passed": True,
"subjects": ["Math", "Science"]
}
print(data)
Empty Dictionary
Creates an empty dictionary to add data later.
my_dict = {}
print(my_dict)
Dictionary Using dict() Function
Creates a dictionary using the built-in dict() function.
student = dict(name="Rahul", age=21, city="Delhi")
print(student)
What is Dictionary Constructor?
A dictionary constructor is another way to create a dictionary using the built-in dict() function instead of { }.
It is useful when:
Creating dictionaries in a clean format
Converting other data types into a dictionary
Passing key-value pairs as arguments
Syntax of Dictionary Constructor
dict(key1=value1, key2=value2, key3=value3)
Basic Dictionary Constructor
Creates a dictionary using dict() with key-value arguments.
student = dict(name="Amit", age=20, course="Python")
print(student)
Dictionary from List of Tuples
Creates a dictionary by converting a list of key-value tuples.
data = [("name", "Riya"), ("marks", 85), ("grade", "A")]
student = dict(data)
print(student)
Dictionary from Two Lists
Creates a dictionary by combining two lists using zip().
keys = ["name", "age", "city"]
values = ["Rahul", 22, "Mumbai"]
person = dict(zip(keys, values))
print(person)