1.7 Dictionaries and Sets

Loading content...

1.7 Dictionaries and Sets

Module 7 — Dictionaries & Sets | Python for ML 🐍 Module 7 • Python for Machine Learning Store data in key:value pairs and handle unique collections — the backbone of Python data handling and ML configs! Think of a real dictionary (the book). You look up a word (key) and find its meaning (value). 📖 Or imagine a filing cabinet. Each drawer has a label (key) like "Taxes" or "Medical". Inside each drawer is a document (value). You never open drawers at random — you pick the label you need. 🗂️ A Python dictionary is an unordered collection of key:value pairs. Each key is unique, and you use it to look up the associated value instantly. ⚡ 📌 Key = the label (must be unique & immutable). Value = the data stored (can be anything). Pair = one key linked to one value. 🗃️ Filing Cabinet = Dictionary 🔎 Give a key → get the value instantly! 💡 Lists use integer indexes (0, 1, 2…). Dictionaries use meaningful keys ("name", "age"). That's the big difference! ✅ True or False — Activity 1 of 15 A Python dictionary stores data as key:value pairs, where each key must be unique. There are three common ways to create a dictionary in Python. 🛠️ 📝 Method 1: Curly braces { } # 🧑 Student record using curly braces {'name': 'Ali', 'age': 20, 'grade': 'A'} 📝 Method 2: dict() constructor # 📊 ML model scores using dict() scores = dict(KNN=0.85, SVM=0.92, RF=0.89) {'KNN': 0.85, 'SVM': 0.92, 'RF': 0.89} 📝 Method 3: Empty dict, then add # 🔧 Start empty, add later config["learning_rate"] = 0.01 {'learning_rate': 0.01, 'epochs': 100} 🔥 Tip: Keys must be immutable (strings, numbers, tuples). You cannot use a list as a key! 🧠 Multiple Choice — Activity 2 of 15 Which of the following is a valid Python dictionary? 🤔 {"name": "Sara", "age": 20} ["name": "Sara", "age": 20] ("name": "Sara", "age": 20) You have two ways to get a value from a dictionary: square brackets and the .get() method. 🎯 student = {"name": "Ali", "age": 20} print(student["name"]) # ✅ Ali print(student["age"]) # ✅ 20 # print(student["gpa"]) # ❌ KeyError! ⚠️ If the key doesn't exist, dict[key] crashes with a KeyError! student = {"name": "Ali", "age": 20} print(student.get("name")) # ✅ Ali print(student.get("gpa")) # ✅ None (safe!) print(student.get("gpa", 0.0)) # ✅ 0.0 (default) 💡 .get() is safer — it returns None (or a default) instead of crashing! ✍️ Fill in the Blank — Activity 3 of 15 Given student = {"name": "Sara", "gpa": 3.8}, what does student["name"] return? 📝 🧠 Multiple Choice — Activity 4 of 15 What does student.get("phone") return when "phone" key doesn't exist? 🤔 ✏️ Adding, Updating & Deleting Use dict[key] = value. If the key exists, it updates. If it's new, it adds. 🔄 student = {"name": "Ali", "age": 20} print(student) # {'name': 'Ali', 'age': 20, 'grade': 'A'} print(student) # {'name': 'Ali', 'age': 21, 'grade': 'A'} {'name': 'Ali', 'age': 20, 'grade': 'A'} {'name': 'Ali', 'age': 21, 'grade': 'A'} student = {"name": "Ali", "age": 21, "grade": "A"} # 🗑️ del removes a specific key print(student) # {'name': 'Ali', 'age': 21} # 🗑️ .pop() removes and returns the value removed = student.pop("age") print(student) # {'name': 'Ali'} {'name': 'Ali', 'age': 21} 📌 del dict[key] → deletes silently. dict.pop(key) → deletes AND gives you the value back. dict.clear() → empties the entire dictionary. ✅ True or False — Activity 5 of 15 If you assign a value to a key that already exists, the old value is replaced by the new one. ✍️ Fill in the Blank — Activity 6 of 15 To remove the key "age" from a dictionary d, write: ___ d["age"]. What keyword goes in the blank? 🔑 Dictionaries come with powerful built-in methods. Here are the three you'll use most. 🔧 dict_keys(["name", "age"]) [("name","Ali"), ("age",20)] student = {"name": "Ali", "age": 20, "grade": "A"} print(student.keys()) # 📋 All keys print(student.values()) # 📦 All values print(student.items()) # 🔗 Key-value pairs print(len(student)) # 🔢 Count: 3 print("name" in student) # 🔍 True dict_keys(['name', 'age', 'grade']) dict_values(['Ali', 20, 'A']) dict_items([('name', 'Ali'), ('age', 20), ('grade', 'A')]) 🧠 Multiple Choice — Activity 7 of 15 What does .items() return from a dictionary? 📦 A list of (key, value) tuples The length of the dictionary

Subject: Python for Machine Learning | Chapter: Chapter 1: Python Essentials

1.6 Lists and List Comprehensions Chapter 1: Python Essentials 1.8 String Operations
Topics
Chapter 1: Python Essentials
Chapter 2: Python for Data Science
© Copyright © 2020 ALGOPK . All Rights Reserved.