This Hash Tables lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A hash table finds a value from its key without scanning every item. A Python dict is a hash table.
Keys must be unchanging values, such as text, numbers, or tuples. A list cannot be a key.
Example 1: Start here
A missing key raises KeyError. Use in or get when the key might be absent.
table = {} # a dictionary; each key has one value
table["Meera"] = "Python" # change this one field
print(table["Meera"])
print("Arun" in table) # in is True when the value is found
Example 2: Walk the values
Hash Tables starts by visiting one value at a time. Read the printed lines from top to bottom.
values = [26, 3, 11, 7] # a list; the values stay in this order
for value in values: # repeat the indented lines once per value
print(value)
Example 3: Keep the largest
Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.
values = [26, 3, 11, 7] # a list; the values stay in this order
best = values[0] # the first value
for value in values: # repeat the indented lines once per value
if value > best: # run the indented lines only when this is true
best = value # another name for the same value
print(best)
Example 4: Search for a target
A search asks one yes-or-no question: is the target in the collection? Hash Tables builds on that question.
values = [3, 26, 11] # a list; the values stay in this order
target = 26 # a whole number
print(target in values) # in is True when the value is found
