
![]() |
@wtf | |
Create your own contact book |
||
1
Replies
24
Views
1 Bookmarks
|
![]() |
@wtf | 22 days |
Today, let's move on to the next topic in the Python Coding Challenge: *Dictionaries & Sets* *What is a Dictionary in Python?* A dictionary is an unordered, mutable collection that stores data in key-value pairs. *Example:* student = name: Amit, age: 21, course: Python print(student[name]) Output: Amit - Keys must be unique and immutable (like strings, numbers). - Values can be anything: strings, numbers, lists, or even other dictionaries. *Common Dictionary Methods:* student.get(age) Returns 21 student.keys() Returns all keys student.values() Returns all values student.items() Returns key-value pairs student[grade] = A+ Adds a new key-value pair *What is a Set in Python?* A set is an unordered collection of unique elements. *Example* : numbers = 1, 2, 3, 4, 4, 2 print(numbers) Output: 1, 2, 3, 4 — no duplicates - Sets remove duplicates automatically. - Useful for membership checks, uniqueness, and set operations (union, intersection). ✅ *Real-Life Project: Contact Book using Dictionary* - Build a CLI-based contact book where users can: - Add new contacts (name, phone) - View all contacts - Search by name - Delete a contact *Python Code:* contacts = while True: print(n1. Add Contactn2. View Alln3. Searchn4. Deleten5. Exit) choice = input(Enter choice: ) if choice == '1': name = input(Name: ) phone = input(Phone: ) contacts[name] = phone print(Contact saved!) elif choice == '2': for name, phone in contacts.items(): print(fname : phone) elif choice == '3': name = input(Enter name to search: ) if name in contacts: print(fname's phone: contacts[name]) else: print(Contact not found.) elif choice == '4': name = input(Enter name to delete: ) if name in contacts: del contacts[name] print(Deleted successfully.) else: print(No such contact.) elif choice == '5': break else: print(Invalid choice.) |
||


