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 ___.

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?
#
# It only prints as "1, 2, 3" because hashing ignores duplicates within the list/set/dictionary

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
#
# They are similar forms of storing data and sets are used in hashmaps and hashtables
{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, Strings, Integers, and a Dictionary
# A dictionary can h0ld more dictionaries

# 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?
#
# Make an if statement when adding the albumn to check if the producer's name matches andy of the names in the dictionary
# Set statement also works more effectively

# 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': {'Taylor Swift', 'Joel Little', 'Frank Dukes', 'Jack Antonoff', 'Louis Bell'}}
lover_album["tracks"].update({19: "All Of The Girls You Loved Before"})

# How would add an additional genre to the dictionary, like electropop? 
# 
# Make sure the albumn directory is set to "genre" then .update({19: "All Of The Girls You Loved Before"})

# 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': {'Taylor Swift', 'Joel Little', 'Frank Dukes', 'Jack Antonoff', 'Louis Bell'}}
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
#
# Alright
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: {'Taylor Swift', 'Joel Little', 'Frank Dukes', 'Jack Antonoff', 'Louis Bell'}
for k,v in lover_album['tracks'].items():
    print(str(k) + " : " + str(v))
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
#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()))

#earch()

# This is a very basic code segment, how can you improve upon this code?
#
# I can improve the code by removing the need for iteration and loobs by using list comprehension and making the code more straightforward. 

def search():
    search = input("What would you like to know about the album?")
    print(lover_album.get(search.lower(), "Invalid Search"))

search()
Taylor Swift
fearless_album = {
    "title": "fearless",
    "artist": "Taylor Swift",
    "year": 2021,
    "genre": ["Pop", "Country-Pop", "Folk", "Rock"],
    "tracks": {
        1: "Fearless",
        2: "Fifteen",
        3: "Love Story",
        4: "Hey Steven",
        5: "White Horse",
        6: "You Belong with Me",
        7: "Breathe (featuring Colbie Caillat)",
        8: "Tell Me Why",
        9: "You're Not Sorry",
        10: "The Way I Loved You",
        11: "Forever & Always",
        12: "The Best Day",
        13: "Change",
    }
}

rush_album = {
    "title": "The Slow Rush",
    "artist": "Tame Impala",
    "year": 2020,
    "genre": ["Dystopian Synth", "Indie Rock"],
    "tracks": {
        1: "One More Year",
        2: "Instant Destiny",
        3: "Borderline",
        4: "Posthumus Forgivness",
        5: "Breathe Deeper",
        6: "Tomorrow's Dust",
        7: "On Track",
        8: "Lost in Yesterday",
        9: "Is It True",
        10: "It Might Be time",
        11: "Glimmer",
        12: "One More Hour",
        13: "Patience",
    }
}

album_choice = input("Which album would you like to listen to? (Fearless or The Slow Rush): ")
song_choice = input("Which song would you like to listen to? ")

if album_choice == 'Fearless':
    print(f"Playing {fearless_album['tracks'][int(song_choice)]} by {fearless_album['artist']} from {fearless_album['title']}")
elif album_choice == 'The Slow Rush':
    print(f"Playing {rush_album['tracks'][int(song_choice)]} by {rush_album['artist']} from {rush_album['title']}")
else:
    print("Invalid album choice.")
Playing The Best Day by Taylor Swift from fearless

Hacks

  • Answer ALL questions in the code segments
  • Create a diagram or comparison illustration (Canva).
    • 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

My Favorite Taylor Swift Song...

  • Answer

    • Forever & Always
  • Reasoning

    • Forever & Always feels more laid back and relaxed while telling a story about her personal experiences in life with love and intimacy (breakup with Joe Jonas). The songe felt raw and authentic rather than being another song made to be a catchy hit. Alongside the storytelling, the music is absolutely gorgeous and very well compliments the story by following that somewhat somber yet hopeful theme. I like the drums and acoustic specifically of this song and basically of any song which is why this is my favorite Taylor Swift song. I don't listen to "Queen Tay Tay" that very often and sometimes just gets randomly shuffled whenever I play spotify but always a good time when I'm listening to it.
import requests
from concurrent.futures import ThreadPoolExecutor
import os

url = "https://flask.nighthawkcodingsociety.com/api/jokes/like/{joke_id}"
joke_id = "1"

def like_joke(joke_id):
    with requests.put(url.format(joke_id=joke_id), stream=True) as response:
        pass

max_workers = max(1, int(os.cpu_count()*2 / 3))

with ThreadPoolExecutor() as executor:
    while True:
        executor.submit(like_joke, joke_id)
Canceled future for execute_request message before replies were done
The Kernel crashed while executing code in the the current cell or a previous cell. Please review the code in the cell(s) to identify a possible cause of the failure. Click <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details.