Data Structures

HashMap and Set


You just learned how the HashMap works, but you don't have to implement a HashMap yourself. Python has a built-in HashMap, and in this lesson we'll go over how to use it.


HashMaps are like Arrays, but where you store data by keys of your choice, instead of by index 0, 1, 2, 3. To create a HashMap, you specify both the key and value of each element. Here's an example:

You can read from a HashMap like this:

You can write to it like this:

You can also insert an element like this:

You can delete an element like this, but it's uncommon:

HashMaps don't have to shift elements over when you insert/delete, unlike the Array. This is because the position of every element in a HashMap is independent from all the other elements - see the summary on how elements in HashMaps are stored. This means all actions on a HashMap are fast, taking O(1)O(1) time on average.

Read/Write Complexity O(1)O(1)

Insert/Delete Complexity O(1)O(1)


Sets are just HashMaps where you don't specify values. You only specify keys. Behind the scenes, they essentially just create a HashMap where every value is True. They're just for convenience - you could use a HashMap instead if you felt like it.

Here's how you create a Set:

Here's more syntax for Sets:

Read Complexity O(1)O(1)

Add/Remove Complexity O(1)O(1)

Important: Python only allows the keys of HashMaps and Sets to be immutable - they can be strings, numbers, or tuples, but they can't be mutable types like Arrays. Python thought it would be too confusing to let you use an object as a key and then change it later.

Mark as Completed:
Test your code to get an output here!