Dictionaries and Sets
A dictionary stores key: value pairs inside curly brackets. You look up a value by its key, like finding a word in a dictionary.
A list is good when order matters. But often you want to find something by name, not by position: "How many shoes are in stock?" With a list you'd have to search item by item. A dictionary jumps straight to the answer, because every value is stored under a key.
Real-life examples: a phone's contact list (name -> number), a menu card (dish -> price), a student's marks (subject -> marks). Each key appears only once - if you store a new value under an existing key, it replaces the old one.
Dictionaries are one of the most used tools in Python. Data from websites and apps (JSON) looks exactly like Python dictionaries, so you'll meet them again and again.
Notice two ways to read a value. stock["Shoes"] is direct, but if the key doesn't exist, Python stops with a KeyError. stock.get("Pen", 0) is safer: it returns your default value instead. The in check tells you if a key exists before you use it.
Looping through a dictionary
Looping over a dictionary is how you build reports: print every product with its price, add up all values, or find the most expensive item. .items() gives you both the key and the value each time; .keys() and .values() give just one side.
Sets
A set keeps only unique values. It is handy for removing duplicates.
Sets answer questions like "Which different cities did our orders come from?" or "Has this coupon been used before?". Checking if something is in a set is very fast, even with millions of items. Sets have no order, so you can't use an index like tags[0] - use sorted() if you need a fixed order.
dict.get(key, default) is safer than dict[key]: it gives the default instead of an error when the key is missing.- A dictionary maps keys to values:
{"Shoes": 10}. Keys are unique. - Use
d.get(key, default)to avoid errors for missing keys. .items()loops over keys and values together.- A set keeps unique values only - great for removing duplicates.
