Data Structures- Hashmaps, Sets, Hash Tables, Hashing and Collisions
Observing hashmaps with python dictionaries
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 0(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?
#
#
# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
#
#
- The
set()
function got rid of the duplicates.
What do you notice in the output?
The code creates a set object named "my_set" containing the elements [1, 2, 3, 2, 1]. Since sets cannot contain duplicate elements, the duplicates are automatically removed, and the output of the print statement shows the unique elements of the set in no particular order.
Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
Hash tables are used to implement dictionaries and sets in many programming languages. A hash table is a data structure that allows for efficient lookup, insertion, and deletion of elements by computing an index into an array using a hash function. Similarly, a set is a collection of unique elements, and it can be implemented as a hash table where each element is hashed to a unique index in the table.
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?
#
#
# Printing the dictionary
print(lover_album)
-
Lists and dictionaries.
- Genre(s)
- Track(s)
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"] = 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?
lover_album["producer"] = {producer for producer in ['Taylor Swift', 'Jack Antonoff', 'Joel Little', 'Taylor Swift', 'Louis Bell', 'Frank Dukes']}
# 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?
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
print(str(k) + ": " + str(v))
# Write your own code to print tracks in readable format
print("Tracks on the {} album by {}: ".format(lover_album["title"], lover_album["artist"]))
for track_number, track_name in lover_album["tracks"].items():
print("{}. {}".format(track_number, track_name))
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?
#
#
Improved Version of the Above Code
I used a different name for the function to avoid conflicts with the user input variable. I also passed the lover_album dictionary as an argument to the function instead of relying on a global variable.The function first converts the user input to lowercase using the lower() method, to avoid case-sensitivity issues. Then, it checks if the input key is present in the album dictionary using the in keyword. If it is, it prints the corresponding value. Otherwise, it prints an error message. Overall, this version is more robust, user-friendly, and follows better coding practices
def search_album(album_dict):
search_key = input("What would you like to know about the album? ").lower()
if search_key in album_dict:
print(album_dict[search_key])
else:
print("Invalid search.")
search_album(lover_album)
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 TS song is "I Know Places", because:
-
I don't know many of her songs.
-
It has a nice rhythm and beat.
kid_a_album = {
"title": "Kid A",
"artist": "Radiohead",
"year": 2000,
"genre": ["Electronic", "Experimental"],
"tracks": {
1: "Everything In Its Right Place",
2: "Kid A",
3: "The National Anthem",
4: "How To Disappear Completely",
5: "Treefingers",
6: "Optimistic",
7: "In Limbo",
8: "Idioteque",
9: "Morning Bell",
10: "Motion Picture Soundtrack"
}
}
print(kid_a_album)
okc_album = {
"title": "OK Computer",
"artist": "Radiohead",
"year": 1997,
"genre": ["Alternative rock", "Art rock"],
"tracks": {
1: "Airbag",
2: "Paranoid Android",
3: "Subterranean Homesick Alien",
4: "Exit Music (For a Film)",
5: "Let Down",
6: "Karma Police",
7: "No Surprises",
8: "Lucky",
9: "The Tourist"
}
}
print(okc_album)
in_rainbows_album = {
"title": "In Rainbows",
"artist": "Radiohead",
"year": 2007,
"genre": ["Alternative rock", "Art rock"],
"tracks": {
1: "15 Step",
2: "Bodysnatchers",
3: "Nude",
4: "Weird Fishes/Arpeggi",
5: "All I Need",
6: "Faust Arp",
7: "Reckoner",
8: "House of Cards",
9: "Jigsaw Falling into Place",
10: "Videotape"
}
}
print(in_rainbows_album)
httt_album = {
"title": "Hail to the Thief",
"artist": "Radiohead",
"year": 2003,
"genre": ["Alternative rock", "Art rock"],
"tracks": {
1: "2 + 2 = 5",
2: "Sit Down. Stand Up.",
3: "Sail to the Moon",
4: "Backdrifts",
5: "Go to Sleep",
6: "Where I End and You Begin",
7: "We Suck Young Blood",
8: "The Gloaming",
9: "There There",
10: "I Will",
11: "A Punchup at a Wedding",
12: "Myxomatosis",
13: "Scatterbrain",
14: "A Wolf at the Door"
}
}
print(httt_album)
import random
madlib_template = "The first time I listened to Radiohead's album {}, I felt {} because the music was so {}. My favorite track was {} because it gave me a {}."
albums = [kid_a_album, httt_album, okc_album, in_rainbows_album]
chosen_album = random.choice(albums)
album_title = chosen_album["title"]
album_genre = random.choice(chosen_album["genre"])
album_tracks = chosen_album["tracks"]
chosen_track_num, chosen_track_title = random.choice(list(album_tracks.items()))
madlib_story = madlib_template.format(album_title, random.choice(["a sharp pain in my heart", "proud", "a funeral in my brain", "nothing"]), album_genre, chosen_track_title, random.choice(["heart attack", "sense of patriotism", "series of random goosebumps", "aneurysm"]))
print(madlib_story)