Dictionaries help you store pairs of related information, like names and phone numbers, so you can find things quickly.
0
0
Dictionary creation in Python
Introduction
When you want to link a word to its meaning, like a mini dictionary.
When you need to store settings with names and values, like volume or brightness.
When you want to count how many times each item appears in a list.
When you want to group data by a key, like students by their grade.
Syntax
Python
my_dict = {key1: value1, key2: value2, key3: value3}Keys must be unique and usually are strings or numbers.
Values can be any type: numbers, strings, lists, or even other dictionaries.
Examples
This creates an empty dictionary with no items.
Python
empty_dict = {}A dictionary with keys 'name', 'age', and 'city' storing related information.
Python
person = {"name": "Alice", "age": 30, "city": "New York"}Keys are subjects and values are scores.
Python
scores = {"math": 90, "science": 85, "english": 88}Sample Program
This program creates a dictionary to store a student's name, age, and courses. It then prints each piece of information.
Python
student = {
"name": "John",
"age": 20,
"courses": ["Math", "History", "Science"]
}
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Courses: {', '.join(student['courses'])}")OutputSuccess
Important Notes
You can create dictionaries using the {} syntax or the dict() function.
Keys must be immutable types like strings, numbers, or tuples.
Dictionaries do not keep order before Python 3.7, but from 3.7+ they remember the order items were added.
Summary
Dictionaries store data as key-value pairs for easy lookup.
Keys are unique and values can be any type.
Use curly braces {} to create dictionaries quickly.