Introduction to HashMaps

Hi, and welcome! Today, we'll explore HashMaps, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment.

Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of HashMaps! Today, we'll understand HashMaps and learn how to implement them in Python.

Understanding HashMaps

HashMaps are special types of lists that utilize unique keys instead of indexes. When you know the key (toy's label), you can directly pick up the value (toy). That's how a HashMap works!

Consider an oversized library of books. With HashMaps (which act like the library catalog), you'll quickly locate any book using a unique number (key)!

HashMaps in Python: Dictionaries

Python implements HashMaps through dictionaries. They hold data in key-value pairs, enclosed within {} (curly braces).

Let's create a dictionary, functioning as a catalog for a library:

# Creating a catalog for the library using dictionaries
library_catalog = {'book1': 'A Tale of Two Cities', 
                   'book2': 'To Kill a Mockingbird', 
                   'book3': '1984'}

In this dictionary, book1, book2, and book3 are keys, while the book titles serve as their respective values.

It's important to remember that while dictionary values can be mutable or immutable types, dictionary keys must be of an immutable type (such as strings, numbers, or tuples).

Additionally, dictionaries preserve item order as of Python 3.7—which means that values are stored and retrieved in the same order they were added!

HashMap Operations: Accessing, Updating, and Removing Elements

Dictionaries allow you to access, update, or remove elements:

  1. Accessing Elements: You can retrieve a book's title using its key in a straightforward way: library_catalog['book1'] would return 'A Tale of Two Cities'. But what happens if you try to access a key that isn't present in the dictionary? This would result in a KeyError.

    To prevent such errors, Python dictionaries provide the get() method. It fetches the value for a given key if it exists. If it doesn't, it simply returns None.

    # Using get() to access a book's title
    book1 = library_catalog.get('book1')
    print(book1)  # Output: "A Tale of Two Cities"
    
    # Using get() to access a nonexistent key
    nonexistent_book = library_catalog.get('book100')
    print(nonexistent_book)  # Output: None

    In the example above, get('book1') retrieves the value for the key book1, but get('book100') does not raise an error even though 'book100' does not exist in the dictionary. Instead, it returns None, allowing your program to continue running smoothly.

  2. Adding or Updating Elements: Whether you're adding a new book to the catalog or updating an existing book's title, you'll use the assignment operator (=). This syntax in Python's dictionaries allows for both updating existing key-value pairs and establishing new ones.

    If the specified key exists in the dictionary, the assigned value replaces the existing one. For updating a title: library_catalog['book1'] = 'The Tell-Tale Heart'.

    If the key doesn't exist in the dictionary yet, the operation creates a new key-value pair. For adding a new book: library_catalog['book4'] = 'Pride and Prejudice'.

  3. Removing Elements: If 'book1' no longer exists, you can remove it using del library_catalog['book1'].

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal