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

FivG_Pro

πŸ”° What Is a Function? A function is a reusable block of code that performs a specific task.Instead of repeating code, we can write it once and call it whenever…

Read more

Show7_Pro

🟒 Lesson 6 – Intermediate Level πŸ”° What Is a Module? A module is simply a Python file (.py) containing code (functions, variables, classes) you can reuse in other programs….

Read more

GoldiptvPro

🟒 Lesson 5 – Intermediate Level πŸ”° What Are Exceptions? An exception is an error that occurs during the execution of a program.If not handled, it will stop the program…

Read more

Domingo

🟒 Lesson 4 πŸ”° What Is OOP? Object-Oriented Programming (OOP) is a programming style where you organize code into objects that contain: Python supports OOP using: 🧱 Example: Why Use…

Read more

SHARK_PRO

πŸ”° What Is File Handling? 🟒 Lesson 3 File handling lets your Python programs interact with files on your computer β€” read data from them or save data to them….

Read more

Pro_Click

πŸ”° What Are Lists ? A list is an ordered collection of items stored in a single variable. πŸ“Œ Lists are defined using square brackets []. πŸ§ͺ Example : pythonCopierModifierfruits…

Read more