← All lessons

Hash tables

Sign in · Sign up

Lesson 12.7

A dictionary is a hash table: Python works out an "address" from the key and finds the value almost instantly.

seen = {}

if name in seen:
    print("Already here:", name)
else:
    seen[name] = True
    print("New:", name)
  • access by key — seen[name] — is O(1), unlike target in list, where the whole list is scanned;
  • name in seen is a fast check too;
  • keys must be immutable: a string or a number works, a list does not.

The check gives the list of visits names. For each name print New: <name> if it is seen for the first time, and Already here: <name> if it was there before.

Hint

Keep what you have seen in a dictionary: the name is the key, the value is True.

The check is name in seen. If the name is already there — one message, if not — the other one, and the name is written into the dictionary. That is faster than searching a list every time.