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

Eagle

Lesson 9: Dictionaries in Depth 1. Introduction to Dictionaries Dictionaries are one of the most powerful and flexible data structures in Python.They store data as key-value pairs and are extremely…

Read more

Akratv

Lesson 7 โ€“ Functions and Scope in Python ๐Ÿ“˜ Introduction In Python, lists, tuples, and sets are three important ways to store collections of items. Each has unique features and…

Read more

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