Data Structures- Hashmaps, Sets, Hash Tables, Hashing and Collisions
Observing hashmaps with python dictionaries
- What is a Hashtable/Hashmap?
- What is Hashing and Collision?
- What is a Set?
- Dictionary Example
- Hacks
- Favorite Taylor Swift song
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)__ because each key only has one value. If you know the key, you would know the value.
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 values of a list are outputted as part of a set. Perhaps the set only takes in unique elements
# because although the list has two 2s and 1s, the set only outputs one 1 and 2.
# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
# Sets
# There can not be the same keys in sets and hashmaps.
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?
# Strings, integers, lists, and dictionaries
#
# Printing the dictionary
print(lover_album)
print(lover_album.get('tracks'))
# or
print(lover_album['tracks'])
print(lover_album.get('tracks')[4])
# or
print(lover_album['tracks'][4])
lover_album["producer"] = ['Taylor Swift', 'Jack Antonoff', 'Joel Little', 'Taylor Swift', 'Louis Bell', 'Frank Dukes']
# What can you change to make sure there are no duplicate producers?
# Use a set
#
# Printing the dictionary
print(lover_album)
lover_album["tracks"].update({19: "All Of The Girls You Loved Before"})
# How would add an additional genre to the dictionary, like electropop?
# The code would be something like: lover_album["genre"].append("electropop")
#
# Printing the dictionary
print(lover_album)
for k,v in lover_album.items(): # iterate using a for loop for key and value
if (type(v) == list):
print(str(k) + ": " + str(v[0]))
for i in range(1,len(v)):
print(v[i])
elif (type(v) == dict):
print(str(k) + ": " + str(list(v)[0]) + ": " + str(v.get(1)))
for i in range(2,len(v)+1):
print(str(list(v)[i-1]) + ": " + v.get(i))
else:
print(str(k) + ": " + str(v))
# Write your own code to print tracks in readable format
#
#
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?
#
#
def add():
track = input("Enter favorite track number:")
print("Enter favorite track number, enter finish to end:")
favorite_tracks = {}
while track != "finish":
favorite_tracks.update({int(track): lover_album["tracks"][int(track)]})
track = input("Enter favorite track number:")
return favorite_tracks
decision = input("Would you like to search or add to list?")
print("Would you like to search or add to list?")
if decision == "add":
print("Favorite tracks: " + str(add()))
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
Reponse
- 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
alan_walker_album = {
"title": "Different World",
"artist": "Alan Walker",
"year": 2018,
"genre": ["EDM"],
"tracks": {
1: {"song": "Diamond Heart", "time": "4:00"},
2: {"song": "Faded", "time": "3:32"},
3: {"song": "Interlude", "time": "1:19"},
4: {"song": "Faded (Interlude)", "time": "0:42"},
5: {"song": "Sing Me to Sleep", "time": "3:08"},
6: {"song": "All Falls Down", "time": "3:19"},
7: {"song": "Lily", "time": "3:16"},
8: {"song": "Do It All for You", "time": "2:55"},
9: {"song": "Alone", "time": "2:41"},
10: {"song": "Darkside", "time": "3:32"},
11: {"song": "Different World", "time": "3:23"},
12: {"song": "Lonely", "time": "3:36"},
13: {"song": "Lost Control", "time": "3:42"},
14: {"song": "Intro", "time": "1:16"},
15: {"song": "I Don't Wanna Go", "time": "2:42"}
}
}
# Printing the dictionary
print(alan_walker_album)
playlist = []
addSong = input("What song would you like to add to your playlist?")
while addSong != "finish":
for i in range(len(alan_walker_album["tracks"])):
songName = alan_walker_album["tracks"][i+1]["song"]
if addSong.lower() == songName.lower():
playlist.append({"song": songName, "time": alan_walker_album["tracks"][i+1]["time"]})
break
if (addSong.lower() != songName.lower()) and i == 14:
print("Song not found in album")
addSong = input("What song would you like to add to your playlist?")
print("Your playlist is: " + str(playlist))
totalTime = 0
minutes = 0
seconds = 0
for i in range(len(playlist)):
minutes += int((playlist[i]["time"].split(':')[0]))
seconds += int((playlist[i]["time"].split(':')[1]))
minutes += (seconds//60)
seconds = (seconds % 60)
print("The total time of your playlist is: " + str(minutes) + ":" + str(seconds))
Favorite Taylor Swift song
This was a hard one to choose. There are quite a few Taylor Swift songs that I like, from I Knew You Were Trouble to Blank Space to Mean. I'd say that I have a favorite song for each genre of Swift's song, which is why it took a lot of contemplation to select my favorite song. In the end, I would say that my favorite Taylor Swift song is Me! firstly because of its catchy tune. One of the main things I like about her song is its message, how it empathizes accepting yourself and liking yourself because of your uniqueness.
But moreover, the reason why I like this song so much is because it showed Swift's transition from her Reputation album to Lover. I remember listening to Look What You Made Me Do when I was 11 and back then, I was pretty shocked at the lyrics. Back then, I couldn't understand what she was singing about and felt that the song was depressing. Many years later, I understand better about the pain that she communicates through that song. I remember watching Miss Americana with a friend a few years ago, and in that documentary, Swift recounted her career with how she started all the way to her producing the Lover album. The things that stuck with me the most was how much she was dealing with during the time she composed Reputation. She was struggling with anexoria, along with the burden of peparazzi and always having the desire to please her fans, even if it came at the cost of her own mental well being. I felt a lot of sympathy for her, and her documentary made her seem like a normal person. It showed that a celebrity, who typically seems to have it all, can also have a vulnerable state, and also experiences problems just like us normal people.
So after seeing her struggle through Reputation, I was happy for how she got better and moved on to creating positive, peppy songs in her Lover album. I think Me! really showed how she was embracing herself and accepting that even if she is not perfect, she is still ok with it. It felt like Swift's comeback from Reputation, and I think Me! is a perfect example of her emerging victorius from the her hardships during the Reputation era.