Lesson 1

Essentials of HashMaps in Python

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:

Python
1# Creating a catalog for the library using dictionaries 2library_catalog = {'book1': 'A Tale of Two Cities', 3 'book2': 'To Kill a Mockingbird', 4 '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.

    Python
    1# Using get() to access a book's title 2book1 = library_catalog.get('book1') 3print(book1) # Output: "A Tale of Two Cities" 4 5# Using get() to access a nonexistent key 6nonexistent_book = library_catalog.get('book100') 7print(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'].

Dictionary Methods: items(), keys(), values(), and others

Python's dictionaries offer several useful methods to interact with and manage your data:

  1. Checking for a Key: Ensure if a given book is present in your catalog using 'book1' in library_catalog.

  2. Accessing all Key-Value Pairs: Use the items() method to retrieve all key-value pairs in the dictionary as tuples in a list-like object. This will come in handy when you need to examine all the data you have stored.

    Python
    1all_books = library_catalog.items() 2# all_books now holds: dict_items([('book1', 'A Tale of Two Cities'), ('book2', 'To Kill a Mockingbird'), ('book3', '1984')])
  3. Accessing all Keys and Values: The keys() and values() methods return list-like objects consisting of all keys and all values in the dictionary, respectively.

    Python
    1# Getting all keys 2all_keys = library_catalog.keys() 3# all_keys now holds: dict_keys(['book1', 'book2', 'book3']) 4 5# Getting all values 6all_values = library_catalog.values() 7# all_values now holds: dict_values(['A Tale of Two Cities', 'To Kill a Mockingbird', '1984'])
  4. Iterating over the Dictionary: Loop through your dictionary to access each key-value pair in turn:

    Python
    1# Looping over the dictionary 2for key, value in library_catalog.items(): 3 print(key, ":", value)

    When run, this code prints:

    1book1 : A Tale of Two Cities 2book2 : To Kill a Mockingbird 3book3 : 1984

    This looping method is useful if you need to process or analyze all entries in your dictionary in some way.

Keep in mind that dictionary methods return "list-like" objects, but these aren't actual lists. They provide a dynamic view on the dictionary's entries, which means that any changes to the dictionary will be reflected in these objects. If you need a real list, you can simply transform these list-like objects into an actual list by using list() like list(library_catalog.keys()).

Diving Deeper: Understanding Time Complexity

HashMaps are popular because they save time! Operations like addition, update, and locating elements take constant time, O(1), which means they require nearly the same amount of time regardless of the library size.

Lesson Summary and Practice

Well done! You've mastered HashMaps, understood Python's implementation of HashMaps through dictionaries, learned their operations, and grasped the concept of time complexity. Now, gear up for some practice exercises to reinforce your learning. Happy Coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.