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), constant.

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([4, 1, 2, 3, 2, 1])
print(my_set) 
{1, 2, 3, 4}
  • What do you notice in the output? I notice that it only printed each number once, not including duplicates. So, since there was already a 1 and 2 before, it didn't print the other 1s and 2s out. This is the doing of the set function. I also added a four at the beginning to test the set function out, and I noticed that it automatically orders the numbers from least to greatest.

  • Why do you think Sets are in the same tech talk as Hashmaps/Hashtables? Similarly to sets, dictionaries also can't have duplicate keys.

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"
    }
}

# 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'}}
  • What data structures do you see? I see strings, integers, lists, and the dictionary (inside another dictionary). A dictionary can hold many different data types or even data structures.
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'])

# 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': {'Jack Antonoff', 'Taylor Swift', 'Joel Little', 'Louis Bell', 'Frank Dukes'}}
  • What can you change to make sure there are no duplicate producers? We could make the list have a set to make sure there are no duplicates within the list. Now, there will only be one Taylor Swift instead of the previous two.
lover_album["tracks"].update({19: "All Of The Girls You Loved Before"})
lover_album["genre"].append("Electropop")

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop', 'Electropop'], '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': {'Jack Antonoff', 'Taylor Swift', 'Joel Little', 'Louis Bell', 'Frank Dukes'}}
  • How would add an additional genre to the dictionary, like electropop? You can use .append to add to the "genre" key. See above for addition of electropop.
#for k,v in lover_album.items(): # items keyword, using a for loop for key and value
#    print(str(k) + ": " + str(v))

# Write your own code to print tracks in readable format

# Print the dictionary in a readable format with capitalized keys and values
for key, value in lover_album.items():
    if key == "tracks":
        print(f"{key.capitalize()}:")
        for track_number, track_title in value.items():
            print(f"  {track_number}. {track_title}")
    elif key == "producer" or key == "genre":
        print(f"{key.capitalize()}: {', '.join(value)}")
    else:
        print(f"{key.capitalize()}: {value}")
Title: Lover
Artist: Taylor Swift
Year: 2019
Genre: Pop, Synth-pop, Electropop
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: Jack Antonoff, Taylor Swift, Joel Little, Louis Bell, Frank Dukes

To make it more readable, I wanted to capalize letters where appropriate, remove uncessesary things like brackets and quotation marks, and list all the tracks from up to down so it's easier to read.

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', 19: 'All Of The Girls You Loved Before'}
def search1():
    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()))

# This is a very basic code segment, how can you improve upon this code?
def search():
    choice = []
    for k, v in lover_album.items():
        choice.append(k)
    search = input("What would you like to know about the album?: " + ", ".join(choice))
    if lover_album.get(search.lower()) == None:
        print("Invalid Search")
    else:
        dict = lover_album.get(search.lower())
        if search == "tracks":
            print(f"{search.capitalize()}:")
            for track_number, track_title in dict.items():
                print(f"  {track_number}. {track_title}")
        elif search == "producer" or search == "genre":
            print(f"{search.capitalize()}:", dict)
        else:
            print(f"{search.capitalize()}:", dict)

search()
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

First, the question is very vague. It just asks what I would like to known about the album, which is so broad and if you didn't know what was in the dictionary it could be hard to determine what wouldn't be an invalid search. So I displayed the options, which are all the keys.

Also, I formatted the data based on what they chose, making it easier to read. This is the same idea as the readability print code block I did above.

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? This is an image
    • Dictionary vs List
      This is an image
  • Expand upon the code given to you, possible improvements in comments See code above

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

My favorite Taylor Swift song is definitely Blank Space. For me, it's an OG and it takes me back.

I first discovered the song when I was in 2nd grade. Every Tuesday, I would ride a bus early in the morning to my before-school program. I remember each time I would ride the bus, Blank Space would play on the bus radio. I clearly remember each time I would lean my head agains the bus window and hum along to the song because I thought it was really catchy. For a long time, I didn't know what the name of the song was and I was trying to find it by searching up the lyrics. Specifically, I remember thinking that the "got a long list of ex-lovers" part was something about Starbucks... so whenever I searched this up I couldn't find what song it was. However, I finally finally found out the name of the song by watching the Blank Space YouTube video. Blank Space was the first Taylor Swift song I encountered, and after finding out the name, I got more into her music.

I used to be a big fan of Taylor Swift when I was younger, especially in elementary school. Though my music taste has changed over the years and I'm not too much of a "Swiftie" these days, several of my friends LOVE Taylor Swift. I often sing or listen along with my friends when they play her songs. And whenever I hear Blank Space, it's very reminiscing and nostalgic for me. It definitely reminds me of the "good old days" (even though I'm not even that old)... listening to it on the bus is a very core memory for me.

  • Build your own album showing features of a python dictionary

This is pretty similar to the lover_album dictionary above, I created a dictionary for the Who Really Cares Album by TV Girl. There are a few more/different elements. TV girl is a band, so I included the members with the band name as well. Now there is another nested dictionary under artist, along with tracks. I also printed it with format.

WhoReallyCares_album = {
    "title": "Who Really Cares",
    #nested dictionary here
    "artist": {"Band":"TV Girl", "Members": ["Brad Petering, Jason Wyman, Wyatt Harmon"]},
    "year": 2018,
    "genre": ["Indie rock", "Indie pop", "Electronica", "Pop"],
    #nested dictionary here too
    "tracks": {
        1: "Taking What's Not Yours",
        2: "Song About Me",
        3: "Cigarettes out the Window",
        4: "Till You Tell Me to Leave",
        5: "Not Allowed",
        6: "(Do The) Act Like You Never Met Me",
        7: "Safeword",
        8: "For You",
        9: "Loving Machine",
        10: "Heaven Is a Bedroom"
    }
}

# Printing the dictionary
# accessing dictioanry
for key, value in WhoReallyCares_album.items():
    if key == "tracks" or key == "artist":
        print(f"{key.capitalize()}:")
        # here, you can see the accessing of the nested diciontary from tracks and artist
        for k, v in value.items():
            print(f"  {k}: {v}")
    elif key == "producer" or key == "genre":
        print(f"{key.capitalize()}: {', '.join(value)}")
    else:
        print(f"{key.capitalize()}: {value}")
Title: Who Really Cares
Artist:
  Band: TV Girl
  Members: ['Brad Petering, Jason Wyman, Wyatt Harmon']
Year: 2018
Genre: Indie rock, Indie pop, Electronica, Pop
Tracks:
  1: Taking What's Not Yours
  2: Song About Me
  3: Cigarettes out the Window
  4: Till You Tell Me to Leave
  5: Not Allowed
  6: (Do The) Act Like You Never Met Me
  7: Safeword
  8: For You
  9: Loving Machine
  10: Heaven Is a Bedroom