Dictionaries
Python Dictionaries: The "Label Maker" of Code
Imagine you have a real-life dictionary. To find a word’s meaning, you don’t look at page numbers; you look for the Word itself. In Python, a dictionary works exactly the same way using Key-Value pairs.
What is a Dictionary?
A dictionary is a collection that is ordered (in newer Python versions) and changeable.
-
Key-Value Pairs: Every piece of data has a "Key" (the label) and a "Value" (the information).
-
Unique Keys: Every key must be unique—you can't have two labels with the same name!
-
Curly Braces: We create dictionaries using { } and colons : to connect keys to values.
-
Fast Lookup: You can find a value instantly just by knowing its key. It’s like searching for a friend’s name in your phone contacts!
Real-World Dictionary Scenarios
-
Phone Book: (Name → Phone Number)
-
Fruit Stall: ("Apple" → $2, "Banana" → $1)
-
Student Card: ("Name" → "Ram", "Grade" → 5, "Roll No" → 12)
-
Game Inventory: ("Potions" → 5, "Swords" → 2)What is a Dictionary?
How it Looks (Syntax & Examples)
The Pattern:
dict_name = {"key1": value1, "key2": value2}
Example 1: Finding Information
student = {"name": "Ram", "marks": 90}
print(student["name"])
Output: Ram
Example 2: Adding New Information
data = {"a": 1, "b": 2}
data["c"] = 3
print(data)
Output: {'a': 1, 'b': 2, 'c': 3}
Summary:
-
Mutable: You can add, change, or delete key-value pairs anytime.
-
No Duplicates for Keys: If you try to use the same key twice, the new value will overwrite the old one.
-
Structured Data: It’s the best tool for keeping related information together in one neat package.