Sets and Dictionaries
Keep distinct members in a set and associate keys with values in a dictionary.
python, sets, dictionaries, keys, membershipTwo different questions
Ask “which fruits are available?” and a set of names can answer. Ask “what is each fruit's price?” and a dictionary can associate each name with a price. A set holds distinct members; a dictionary maps each key to a value. Neither sorts its contents automatically.
set: apple, pear
map: apple → 3 pear → 5
Adding the same set member again does not create a duplicate. Assigning a
new value to an existing dictionary key replaces its previous value.
set() creates an empty set; {} creates an empty dictionary.
Python illustration
fruits = {"apple", "pear"}
fruits.add("apple")
prices = {"apple": 3, "pear": 5}
prices["apple"] = 4
print(len(fruits))
print("apple" in fruits)
print(prices["apple"])
print(prices.get("plum", "not listed"))
Prepared output — not live execution:
2
True
4
not listed
in tests membership. Dictionary membership tests keys, not values. Accessing
an absent key with prices["plum"] raises KeyError; get can provide an
explicit alternative. A stored None is not the same as a missing key.
See the reasoning
Follow the example one step at a time
Follow the lesson's set membership and dictionary update. This is a prepared teaching demonstration, not live code execution.
Start with a set
fruits: {apple, pear}The set represents two distinct members; this diagram does not promise their iteration order.
Choosing and changing
add inserts a set member; discard removes it if present and does nothing
if absent. Use dictionary assignment to add or change a key and del to
remove an existing key. Set iteration order is not a sorting promise;
dictionaries preserve insertion order, but that is not sorted key order.
Set members and dictionary keys must be hashable. See
Hash Tables for the underlying idea and its caveats.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
