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 of my_set only outputs a 1, 2, 3 which are closed within squiggly duplicates, whereas the set had 1, 2, 3, 2, 1. So it looks like it got rid of the duplicates
#

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
# Sets are in the same tech talk as Hashmaps/Hashtables because it sets can't have duplicate values just like some Hashmaps/Hashtables can't have duplicate values.
#
{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?
# Lists, 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?
# you can put the list within set(), edited above
#

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

# How would add an additional genre to the dictionary, like electropop? 
# To add an additional genre to the lover_album dictionary, access the 'genre' key and append the new genre to the list using the append() method.
# 

# 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', 'Louis Bell', 'Frank Dukes', 'Jack Antonoff', 'Joel Little'}}
lover_album['genre'].append('Electropop')

print(lover_album.get('genre'))
['Pop', 'Synth-pop', 'Electropop']
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: {'Taylor Swift', 'Louis Bell', 'Frank Dukes', 'Jack Antonoff', 'Joel Little'}
for k,v in lover_album.items(): # iterate using a for loop for key and value
    if k == 'tracks':
        print(str(k) + ": ")
        for track_num, track_title in lover_album['tracks'].items():
            print("\t" + str(track_num) + ". " + track_title)
        continue
    print(str(k) + ": " + str(v))
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: {'Taylor Swift', 'Louis Bell', 'Frank Dukes', 'Jack Antonoff', 'Joel Little'}
for k,v in lover_album.items(): # iterate using a for loop for key and value
    if k == 'genre':
        print(str(k) + ": ")
        for genre in lover_album['genre']:
            print("\t- " + genre)
        continue
    if k == 'tracks':
        print(str(k) + ": ")
        for track_num, track_title in lover_album['tracks'].items():
            print("\t" + str(track_num) + ". " + track_title)
        continue
    if k == 'producer':
        print(str(k) + ": ")
        for producer in lover_album['producer']:
            print("\t- " + producer)
        continue
    print(str(k) + ": " + str(v))
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: 
	- Taylor Swift
	- Louis Bell
	- Frank Dukes
	- Jack Antonoff
	- Joel Little
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?
# See below
#
Taylor Swift

Improvements to the Code Segment

  • The code above can be improved by getting rid of the json that appears when you search the genre, tracks, and producers.
  • Created conditionals based on the keys of lover_album that have additional json within them (genre, tracks, producers)
  • Output information on what could be searched up if the input is not valid
  • Within the key "genre", print out each genre separately so that it is more readable
  • within the key "tracks", make it so you have the choice to look at the list of all the tracks or to search up a specific track based on its number or name
    • if the input is invalid, it will print out "please type 'all' or 'specific' next time"
    • if the input typed is "all" is will print out all the tracks in a numbered list by iterating through the key and values in tracks
    • if the input typed is "specific", the user will be prompted to type in the track number or track name
      • if the input is found, it will input the track number and the track name
      • if the input is invalid, it will input "No matching tracks found"
  • Within the key "producers", it will iterate through all the keys in producer and print it out
def search():
    search_term = input("What would you like to know about the album? ").lower()
    
    # Check for invalid input
    if search_term not in ['title', 'artist', 'year', 'genre', 'tracks', 'producers']:
        print("Invalid search term. Please enter one of: title, artist, year, genre, tracks, producers")
        return
    
    # Handle genre search separately
    if search_term == 'genre':
        print(f"Here are the album's genres: {', '.join(lover_album['genre'])}")
        return
    
    # Handle track search separately
    if search_term == 'tracks':
        track_question = input("Do you want to see all tracks in the album or search for a specific track? (type 'all' for all tracks, 'specific' for specific track)")
        if track_question == "all":
            print("Here are all the tracks in the album:")
            for num, title in lover_album['tracks'].items():
                print(f"\t{num}. {title}")
            return
        elif track_question == "specific":
            track_query = input("Enter a track name or number: ").lower()
            matching_tracks = []
            for num, title in lover_album['tracks'].items():
                if track_query == title.lower() or track_query == str(num):
                    matching_tracks.append((num, title))
            if not matching_tracks:
                print("No matching tracks found")
                return
            else:
                # Print all matching tracks
                for num, title in matching_tracks:
                    print(f"\t{num}. {title}")
                return
        else:
            print("please type 'all' or 'specific' next time")
        
    # Handle producers search separately
    if search_term == 'producers':
        producers = lover_album['producer']
        print("Producers:")
        for producer in producers:
            print("\t- " + producer)
        return
    
    # Otherwise, just return the requested information
    print(lover_album[search_term])

search()
Producers:
	- Taylor Swift
	- Louis Bell
	- Frank Dukes
	- Jack Antonoff
	- Joel Little

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 poster
  • 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 I have not listened Taylor Swift songs in a long time, but the one that brings the most nostalgia is Love Story. I remember that this was one of first songs I remember hearing after I gained awareness as a child in preschool. It reminds me of simple times when I didn't have to do much and there was not many expectations placed on me since I was still only 5 years old.

i = 1
while i < 10:
    print(i)
    i = i + 1
1
2
3
4
5
6
7
8
9
i = 1
while i < 10:
    i = i + 1
    print(i)
2
3
4
5
6
7
8
9
10