What is a Hashtable/Hashmap?

A hashtable is a data structure that with a collection of key-value pairs, where each key maps to a value, and the keys must be unique and hashable.

  • In Python there is a built in hashtable known as a dictionary.

The primary purpose of a hashtable is to provide efficient lookup, insertion, and deletion operations. When an element is to be inserted into the hashtable, a hash function is used to map the key to a specific index in the underlying array that is used to store the key-value pairs. The value is then stored at that index. When searching for a value, the hash function is used again to find the index where the value is stored.

The key advantage of a hashtable over other data structures like arrays and linked lists is its average-case time complexity for lookup, insertion, and deletion operations.

  • The typical time complexity of a hashtable is O(1).

What is Hashing and Collision?

Hashing is the process of mapping a given key to a value in a hash table or hashmap, using a hash function. The hash function takes the key as input and produces a hash value or hash code, which is then used to determine the index in the underlying array where the value is stored. The purpose of hashing is to provide a quick and efficient way to access data, by eliminating the need to search through an entire data structure to find a value.

However, it is possible for two different keys to map to the same hash value, resulting in a collision. When a collision occurs, there are different ways to resolve it, depending on the collision resolution strategy used.

Python's dictionary implementation is optimized to handle collisions efficiently, and the performance of the dictionary is generally very good, even in the presence of collisions. However, if the number of collisions is very high, the performance of the dictionary can degrade, so it is important to choose a good hash function that minimizes collisions when designing a Python dictionary.

What is a Set?

my_set = set([1, 2, 3, 2, 1])
print(my_set)  

# What do you notice in the output?
# the output uses the same values as my_set, except removes any duplicates
# outputs a list

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
# A set cannot have duplicate values, just like how the values in a hashtable must be unique
#
{1, 2, 3}

Dictionary Example

Below are just some basic features of a dictionary. As always, documentation is always the main source for all the full capablilties.

lover_album = {
    "title": "Lover",
    "artist": "Taylor Swift",
    "year": 2019,
    "genre": ["Pop", "Synth-pop"],
    "tracks": {
        1: "I Forgot That You Existed",
        2: "Cruel Summer",
        3: "Lover",
        4: "The Man",
        5: "The Archer",
        6: "I Think He Knows",
        7: "Miss Americana & The Heartbreak Prince",
        8: "Paper Rings",
        9: "Cornelia Street",
        10: "Death By A Thousand Cuts",
        11: "London Boy",
        12: "Soon You'll Get Better (feat. Dixie Chicks)",
        13: "False God",
        14: "You Need To Calm Down",
        15: "Afterglow",
        16: "Me! (feat. Brendon Urie of Panic! At The Disco)",
        17: "It's Nice To Have A Friend",
        18: "Daylight"
    }
}

# What data structures do you see?
# list-- genre
# dictionary -- tracks

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}}
print(lover_album.get('tracks'))
# or
print(lover_album['tracks'])
{1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}
{1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}
print(lover_album.get('tracks')[4])
# or
print(lover_album['tracks'][4])
The Man
The Man
lover_album["producer"] = set(['Taylor Swift', 'Jack Antonoff', 'Joel Little', 'Taylor Swift', 'Louis Bell', 'Frank Dukes'])
# What can you change to make sure there are no duplicate producers?
# create a set using the set() function

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}, 'producer': {'Joel Little', 'Frank Dukes', 'Louis Bell', 'Jack Antonoff', 'Taylor Swift'}}
lover_album["tracks"].update({19: "All Of The Girls You Loved Before"})

# How would add an additional genre to the dictionary, like electropop? 
# 

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight', 19: 'All Of The Girls You Loved Before'}, 'producer': {'Joel Little', 'Frank Dukes', 'Louis Bell', 'Jack Antonoff', 'Taylor Swift'}}
for k,v in lover_album.items(): # iterate using a for loop for key and value
    print(str(k) + ": " + str(v))

# Write your own code to print tracks in readable format
# 
# 
title: Lover
artist: Taylor Swift
year: 2019
genre: ['Pop', 'Synth-pop']
tracks: {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight', 19: 'All Of The Girls You Loved Before'}
producer: {'Joel Little', 'Frank Dukes', 'Louis Bell', 'Jack Antonoff', 'Taylor Swift'}
def search():
    search = input("What would you like to know about the album?")
    if lover_album.get(search.lower()) == None:
        print("Invalid Search")
    else:
        print(lover_album.get(search.lower()))

search()

# This is a very basic code segment, how can you improve upon this code?
# 
#
['Pop', 'Synth-pop']

Hacks

  • Answer ALL questions in the code segments
  • Create a venn diagram or other compare and contrast tool related to hashmaps.
    • What are the pro and cons of using this data structure?
    • Dictionary vs List
  • Expand upon the code given to you, possible improvements in comments
  • Build your own album showing features of a python dictionary

  • For Mr. Yeung's class: Justify your favorite Taylor Swift song, answer may effect seed

HACKS

Venn diagam

Venn Diagram

My own dictionaries

albums = [
    ("Thriller", "Michael Jackson", 1982,   # First album list
     [
         (1, "The Girl Is Mine"),
         (2, "Billie Jean"),
         (3, "The Lady in My Life"),
         (4, "Baby Be Mine"),
         (5, "P.Y.Y."),
         (6, "Human Nature"),
         (7, "Beat It"),
         (8, "Wanna Be Startin’ Somethin’"),   
     ]
     ),

    ("Off the Wall", "Michael Jackson", 1979,   # Second album list
     [
         (1, "Girlfriend"),
         (2, "Workin’ Day and Night"),
         (3, "Don't Stop 'Til You Get Enough"),
         (4, "Burn This Disco Out"),
         (5, "It's the Falling in Love"),
         (6, "Off the Wall"),
         (7, "Get on the Floor"),
         (8, "She’s Out of My Life"),
         (9, "Get on the Floor"),
         (10, "Rock With You"),
     ]
     ),

    ("Bad", "Michael Jackson", 1987,
     [
         (1, "I Just Can't Stop Loving You"),
         (2, "Another Part of Me"),
         (3, "Speed Demon"),
         (4, "Man in the Mirror"),
         (5, "Liberian Girl"),
         (6, "Just Good Friends"),
         (7, "Leave Me Alone"),
         (8, "Bad"),
         (9, "Dirty Diana"),
         (10, "The Way You Make Me Feel"),
         (11, "Smooth Criminal"),
     ]
     ),

]

print("Here are the albums \n 1. Thriller \n 2. Off the Wall \n 3. Bad \n \n ")
album = int(input("Choose an album enter its corresponding number"))
print("Here are the songs from" , album, ": \n \n ")
print(albums[album-1])
song = int(input("Choose a song from your chosen album"))

print("Playing" , albums[album - 1][3][song - 1])
Here are the albums 
 1. Thriller 
 2. Off the Wall 
 3. Bad 
 
 
Here are the songs from 1 : 
 
 
('Thriller', 'Michael Jackson', 1982, [(1, 'The Girl Is Mine'), (2, 'Billie Jean'), (3, 'The Lady in My Life'), (4, 'Baby Be Mine'), (5, 'P.Y.Y.'), (6, 'Human Nature'), (7, 'Beat It'), (8, 'Wanna Be Startin’ Somethin’')])
Playing (2, 'Billie Jean')

Midnights Album

midnights_album = {
    "title": "Midnights",
    "artist": "Taylor Swift",
    "year": 2022,
    "genre": ["Alternative/Indie", "Synth-pop", "Holiday","Pop"],
    "tracks": {
        1: ["Lavender Haze", "Meet me at midnight"],
        2: ["Maroon","When the morning came we were cleaning incense off your vinyl shelf"],
        3: ["Anti-Hero","I have this thing where I get older but just never wiser"],
        4: ["Snow On The Beach (feat. Lana Del Rey)","One night a few moons ago I"],
        5: ["You're On Your Own, Kid","Summer went away, still the yearning stays"],
        6: ["Midnight Rain", "Rain, he wanted it comfortable"],
        7: ["Question...?","I remember"],
        8: ["Vigilante Shit", "Draw the cat eye, sharp enough to kill a man"],
        9: ["Bejewled","Baby love, I think I've been a little too kind"],
        10: ["Labyrinth", "It only hurts this much right now"],
        11: ["Karma","You're talking shit for the hell of it"],
        12: ["Sweet Nothing", "I spy with my little tired eye"],
        13: ["Mastermind","Once upon a time"]
    }
}

# What data structures do you see?
# list-- genre
# dictionary -- tracks

# Printing the dictionary
print(midnights_album)
{'title': 'Midnights', 'artist': 'Taylor Swift', 'year': 2022, 'genre': ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop'], 'tracks': {1: ['Lavender Haze', 'Meet me at midnight'], 2: ['Maroon', 'When the morning came we were cleaning incense off your vinyl shelf'], 3: ['Anti-Hero', 'I have this thing where I get older but just never wiser'], 4: ['Snow On The Beach (feat. Lana Del Rey)', 'One night a few moons ago I'], 5: ["You're On Your Own, Kid", 'Summer went away, still the yearning stays'], 6: ['Midnight Rain', 'Rain, he wanted it comfortable'], 7: ['Question...?', 'I remember'], 8: ['Vigilante Shit', 'Draw the cat eye, sharp enough to kill a man'], 9: ['Bejewled', "Baby love, I think I've been a little too kind"], 10: ['Labyrinth', 'It only hurts this much right now'], 11: ['Karma', "You're talking shit for the hell of it"], 12: ['Sweet Nothing', 'I spy with my little tired eye'], 13: ['Mastermind', 'Once upon a time']}}
for i in midnights_album["tracks"]:
    print("Song #" + str(i) + ": " + midnights_album["tracks"][i][0])
    print("     First lyric: " + "'" + str(midnights_album["tracks"][i][1])+ "'")
    print("     Genres" , midnights_album['genre'])
Song #1: Lavender Haze
     First lyric: 'Meet me at midnight'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #2: Maroon
     First lyric: 'When the morning came we were cleaning incense off your vinyl shelf'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #3: Anti-Hero
     First lyric: 'I have this thing where I get older but just never wiser'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #4: Snow On The Beach (feat. Lana Del Rey)
     First lyric: 'One night a few moons ago I'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #5: You're On Your Own, Kid
     First lyric: 'Summer went away, still the yearning stays'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #6: Midnight Rain
     First lyric: 'Rain, he wanted it comfortable'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #7: Question...?
     First lyric: 'I remember'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #8: Vigilante Shit
     First lyric: 'Draw the cat eye, sharp enough to kill a man'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #9: Bejewled
     First lyric: 'Baby love, I think I've been a little too kind'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #10: Labyrinth
     First lyric: 'It only hurts this much right now'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #11: Karma
     First lyric: 'You're talking shit for the hell of it'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #12: Sweet Nothing
     First lyric: 'I spy with my little tired eye'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']
Song #13: Mastermind
     First lyric: 'Once upon a time'
     Genres ['Alternative/Indie', 'Synth-pop', 'Holiday', 'Pop']