NovaPlayer

Lesson 8: Lists, Tuples, and Sets in Python

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

1. What is a Dictionary in Python?

A dictionary in Python is a collection of key-value pairs.

  • Keys must be unique and immutable (e.g., strings, numbers, tuples).
  • Values can be of any data type.
  • Dictionaries are unordered (Python 3.7+ maintains insertion order).

📌 Example:

student = {
    "name": "Alice",
    "age": 22,
    "courses": ["Python", "Math"],
    "graduated": False
}

print(student["name"])   # Output: Alice

2. Creating Dictionaries

You can create dictionaries in different ways:

# Using curly braces
person = {"name": "John", "age": 30}

# Using dict() constructor
person2 = dict(name="Jane", age=25)

print(person)
print(person2)

3. Accessing and Modifying Elements

student = {"name": "Alice", "age": 22}

# Accessing values
print(student["name"])          # Alice
print(student.get("age"))       # 22
print(student.get("grade", "N/A"))  # Returns "N/A" if key doesn’t exist

# Modifying values
student["age"] = 23
student["city"] = "New York"   # Adds a new key-value pair
print(student)

4. Removing Elements

student = {"name": "Alice", "age": 22, "city": "New York"}

student.pop("age")          # Removes age
del student["city"]         # Removes city
student.clear()             # Clears all elements

5. Useful Dictionary Methods

MethodDescriptionExample
keys()Returns all keysdict.keys()
values()Returns all valuesdict.values()
items()Returns key-value pairs as tuplesdict.items()
update()Updates dictionary with another dictionarydict.update(new_dict)
popitem()Removes last inserted key-value pairdict.popitem()

📌 Example:

student = {"name": "Alice", "age": 22}

print(student.keys())      # dict_keys(['name', 'age'])
print(student.values())    # dict_values(['Alice', 22])
print(student.items())     # dict_items([('name', 'Alice'), ('age', 22)])

6. Looping Through Dictionaries

student = {"name": "Alice", "age": 22, "city": "New York"}

# Looping keys
for key in student:
    print(key, student[key])

# Looping items
for key, value in student.items():
    print(f"{key} => {value}")

7. Nested Dictionaries

Dictionaries can contain other dictionaries.

students = {
    "101": {"name": "Alice", "age": 22},
    "102": {"name": "Bob", "age": 24}
}

print(students["101"]["name"])  # Output: Alice

8. Dictionary Comprehension

# Create dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares)   # {0:0, 1:1, 2:4, 3:9, 4:16}

9. Comparison: Dictionary vs. List

FeatureDictionaryList
Data StorageKey-value pairsOrdered collection of values
AccessO(1) average (by key)O(n) (by searching element)
Keys/IndexesKeys (unique)Integer indexes
Use CaseWhen you need fast lookup by keyWhen you need ordered items

10. Summary

  • Dictionaries store key-value pairs.
  • Keys are unique and immutable.
  • Provides powerful methods like keys(), values(), items().
  • Supports nested dictionaries and dictionary comprehensions.
  • Best for scenarios requiring fast lookups and mapping relationships.

⬇️ Download NovaPlayer تحميل Server 1 ⬇️ Download NovaPlayer تحميل Server 2 ⬇️ Download NovaPlayer تحميل Server 3

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