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

FlyFeditv

๐Ÿ“˜ Introduction In this project, youโ€™ll create a command-line Expense Tracker that allows users to: โœ… Add expenses with category, amount, and descriptionโœ… View total spending and category breakdownโœ… Automatically…

Read more

NetCinFly

๐Ÿ“˜ Introduction In this project, youโ€™ll develop a Student Grades Analyzer in Python that can: This project helps you strengthen your skills with lists, dictionaries, loops, and data analysis logic….

Read more

Eagle_Pro

๐ŸŒ Introduction In this project, youโ€™ll create a Web Scraper App in Python that extracts quotes, authors, and tags from a live website.Youโ€™ll use the BeautifulSoup and Requests libraries to…

Read more

Cobra_Pro

๐ŸŒฆ๏ธ Introduction In this project, youโ€™ll build a Weather App in Python that retrieves live weather information from an online API.Youโ€™ll learn how to work with HTTP requests, JSON data,…

Read more

Show7-Pro

Concepts Covered: ๐ŸŽฏ Objective: Create a simple, text-based contact book application that allows users to: ๐Ÿ’ก Code (contact_book.py): ๐Ÿง  Example Usage Console Output Example: ๐Ÿ’พ Notes โฌ‡๏ธ Download Show7-Pro ุชุญู…ูŠู„…

Read more

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