ZinaTv

🟒 Lesson 2 – Intermediate Level

πŸ”Ή Python Dictionaries: Storing and Accessing Key-Value Data

The current image has no alternative text. The file name is: IMG_20250726_020426-scaled.jpg

πŸ”° What Is a Dictionary?

A dictionary in Python is a data structure that stores data in key-value pairs, like this:

pythonCopierModifierperson = {
    "name": "Ali",
    "age": 25,
    "city": "Rabat"
}

Each entry has:

  • A key (like "name")
  • A value (like "Ali")

πŸ“Œ Dictionaries use curly braces {}, and keys must be unique.


🧩 Why Use Dictionaries?

  • πŸ”‘ Easy to look up values using a key.
  • βœ… Better for structured data (e.g. profiles, settings).
  • ⚑ Faster than lists for some types of lookup operations.

βœ… Creating a Dictionary

pythonCopierModifierstudent = {
    "name": "Sara",
    "grade": "A",
    "age": 18
}

πŸ” Accessing Values

pythonCopierModifierprint(student["name"])     # Output: Sara
print(student["grade"])    # Output: A

πŸŸ₯ ⚠️ If the key doesn’t exist, Python will raise a KeyError.

βœ… Safer way using .get():

pythonCopierModifierprint(student.get("email", "Not provided"))

πŸ–ŠοΈ Adding or Updating Entries

pythonCopierModifierstudent["email"] = "sara@example.com"  # Add new key
student["grade"] = "A+"                # Update value

❌ Removing Items

pythonCopierModifierstudent.pop("age")
print(student)

βœ… Or delete by key:

pythonCopierModifierdel student["email"]

πŸ” Looping Through a Dictionary

πŸ“‹ Loop through keys:

pythonCopierModifierfor key in student:
    print(key, "β†’", student[key])

πŸ“‹ Loop through key-value pairs:

pythonCopierModifierfor key, value in student.items():
    print(f"{key}: {value}")

πŸ“‹ Loop through just values:

pythonCopierModifierfor value in student.values():
    print(value)

🧠 Dictionary Functions Summary:

FunctionWhat It Does
dict.get(key, default)Returns value or default if key missing
dict.items()Returns key-value pairs
dict.keys()Returns all keys
dict.values()Returns all values
dict.pop(key)Removes a key
key in dictChecks if a key exists

πŸ§ͺ Exercise 1:

Write a program that:

  • Creates a dictionary called contact.
  • Asks the user to enter a name, phone, and email.
  • Stores them as key-value pairs.
  • Then prints the full contact information.
pythonCopierModifiercontact = {}

contact["name"] = input("Enter your name: ")
contact["phone"] = input("Enter your phone number: ")
contact["email"] = input("Enter your email address: ")

print("\nπŸ“‡ Contact Information:")
for key, value in contact.items():
    print(f"{key.capitalize()}: {value}")

πŸ§ͺ Exercise 2 (Challenge):

Create a simple program to store multiple students and their grades.

pythonCopierModifierstudents = {}

for i in range(3):
    name = input(f"Enter student {i+1}'s name: ")
    grade = input(f"Enter {name}'s grade: ")
    students[name] = grade

print("\nπŸŽ“ Student Grades:")
for name, grade in students.items():
    print(f"{name}: {grade}")

πŸ“ Summary:

  • Dictionaries store data in key-value pairs and are perfect for structured data.
  • You can add, update, remove, and access values by their key.
  • Looping over dictionaries is useful for displaying or processing structured data.

⬇️ Download ZinaTv ΨͺΨ­Ω…ΩŠΩ„ Server 1 ⬇️ Download ZinaTv ΨͺΨ­Ω…ΩŠΩ„ Server 2

Related Posts

Rapid_tv

πŸ”Ή Introduction The Rock, Paper, Scissors Game is a classic hand game that you can easily build in Python. πŸ‘‰ Rules: πŸ”Ή Code Example πŸ”Ή Example Run πŸ”Ή Concepts Learned…

Read more

VOD-ZalHD

πŸ”Ή Introduction The Number Guessing Game is a classic beginner Python project. πŸ”Ή Code Example πŸ”Ή Example Run πŸ”Ή Concepts Learned πŸ”Ή Summary ⬇️ Download VOD-ZalHD ΨͺΨ­Ω…ΩŠΩ„ Server 1 ⬇️…

Read more

Delux_pro

πŸ”Ή Introduction The To-Do List App is one of the most popular beginner projects. It teaches you how to: πŸ”Ή Code Example πŸ”Ή Features of This App πŸ”Ή Example Run…

Read more

Fam4k

πŸ”° Project Overview A calculator is one of the simplest yet most effective projects to start with in Python.You will learn: ✍️ Step 1: Plan the Calculator We need: πŸ–₯️…

Read more

Speed_HD+

1. Introduction Data visualization helps us understand patterns and insights in data by converting raw numbers into charts and graphs.In Python, the most popular libraries are: 2. Installing Required Libraries…

Read more

Dauo

1. Introduction Web scraping is the process of extracting data from websites. In Python, we commonly use libraries like requests (to fetch web pages) and BeautifulSoup (to parse and extract…

Read more