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.

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

Which characters are used to define a Dictionary in Python?

Python uses curly braces { } to store key-value pairs in a dictionary.

Question 2

In a dictionary, what must be unique?

Keys act like unique IDs; you cannot have two identical keys in one dictionary.

Question 3

How do you access the value '90' from this dictionary: results = {"math": 90, "science": 85}?

You access data by placing the key inside square brackets.

Question 4

What happens if you run my_dict["age"] = 15 on a dictionary that doesn't have an "age" key yet?

Dictionaries are mutable, so assigning a value to a new key simply adds it to the collection.

Question 5

Why are Dictionaries better than Lists for a "Phone Book" app?

Dictionaries provide fast data lookup, making them much more efficient for searching specific labels than a list.

Congratulations!

You've successfully mastered the knowledge check for "Dictionaries."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Sets Next Topic Dictionary Operations