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?
#There are 3 outputs
#They are in ascending order
#No duplicate values

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
# They are the same since they cant have duplicates

Dictionary Example

Below are just some basic features of a dictionary. As always, documentation is always the main source for all the full capablilties.

basketball_teams = {
    "nba": "basketball",
    "top_team": "Bucks",
    "year": 2023,
    "champ-contenders": ["Nuggets", "Grizzlies", "Celtics"],
    "standings": {
        1: "Clippers",
        2: "Knicks",
        3: "Kings",
        4: "Suns",
        5: "Cavs",
        6: "Kings",
        7: "Clippers",
        8: "Sixers",
        9: "Nets",
        10: "Warriors",
        11: "Timberwolves",
        12: "Pelicans",
        13: "Heat",
        14: "Hawks",
        15: "Raptors",
        16: "Lakers",
        17: "Bulls",
        18: "Thunder"
    }
}

# What data structures do you see?
# Lists
# Dictionaries

# Printing the dictionary
print(basketball_teams)
{'nba': 'basketball', 'top_team': 'Bucks', 'year': 2023, 'champ-contenders': ['Nuggets', 'Grizzlies', 'Celtics'], 'standings': {1: 'Clippers', 2: 'Knicks', 3: 'Kings', 4: 'Suns', 5: 'Cavs', 6: 'Kings', 7: 'Clippers', 8: 'Sixers', 9: 'Nets', 10: 'Warriors', 11: 'Timberwolves', 12: 'Pelicans', 13: 'Heat', 14: 'Hawks', 15: 'Raptors', 16: 'Lakers', 17: 'Bulls', 18: 'Thunder'}}
print(basketball_teams.get('standings'))
# or
print("Champ Contenders:")
print(basketball_teams['champ-contenders'])
# Using conditionals to retrieve a random song

answer = input("Will Lakers win the NBA title? ")
if answer.lower() == "never":
    print("Finally a some one that understands basketball.")
else:
    print("Lakers will never win another NBA title!")
basketball_teams["best"] = list(set(['LeBron', 'MJ', 'Kobe', 'LeBron' ]))

# What can you change to make sure there are no duplicate producers?
#
# Use a set to remove duplicates

# Printing the dictionary
print("the best NBA players are:")
print(basketball_teams["best"])
basketball_teams["standings"].update({18: "DNHS"})
basketball_teams["players"] = "Ben, Jaden, Zion"

# How would add an additional genre to the dictionary, like electropop? 
# You cant use update since this is not a dictionary
# "basketball_teams[genre] = electropop"

# Printing the dictionary
print(basketball_teams)
{'nba': 'basketball', 'top_team': 'Bucks', 'year': 2023, 'champ-contenders': ['Nuggets', 'Grizzlies', 'Celtics'], 'standings': {1: 'Clippers', 2: 'Knicks', 3: 'Kings', 4: 'Suns', 5: 'Cavs', 6: 'Kings', 7: 'Clippers', 8: 'Sixers', 9: 'Nets', 10: 'Warriors', 11: 'Timberwolves', 12: 'Pelicans', 13: 'Heat', 14: 'Hawks', 15: 'Raptors', 16: 'Lakers', 17: 'Bulls', 18: 'DNHS'}, 'players': 'Ben, Jaden, Zion'}
for k,v in basketball_teams.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
# 
#
nba: basketball
top_team: Bucks
year: 2023
champ-contenders: ['Nuggets', 'Grizzlies', 'Celtics']
standings: {1: 'Clippers', 2: 'Knicks', 3: 'Kings', 4: 'Suns', 5: 'Cavs', 6: 'Kings', 7: 'Clippers', 8: 'Sixers', 9: 'Nets', 10: 'Warriors', 11: 'Timberwolves', 12: 'Pelicans', 13: 'Heat', 14: 'Hawks', 15: 'Raptors', 16: 'Lakers', 17: 'Bulls', 18: 'DNHS'}
players: Ben, Jaden, Zion
import random

eastteams = {"bucks": "Milwaukee Bucks", "celtics": "Boston Celtics", "nets": "New Jersey Nets", "knicks": "New York Knicks", "sixers": "Philadelphia 76ers", "raptors": "Toronto Raptors", "bulls": "Chicago Bulls", "cavs": "Cleveland Cavaliers", "pistons": "Detroit Pistons", "pacers": "Indiana Pacers", "hawks": "Atlanta Hawks", "hornets": "Charlotte Hornets", "heat": "Miami Heat", "magic": "Orlando Magic", "wizards": "Washington Wizards"}

def search():
    options = list(eastteams.keys())
    search = input(f"What NBA team from the eastern conference do you want to know about? Options: {options}\n")
    search = search.lower()
    if search not in eastteams:
        print("They are not in the eastern conference.")
    else:
        team = eastteams[search]
        print(f"{team} is a team apart of the Eastern Confrence.")
        random_eastteam = random.choice(["LaVine", "Giannis", "Tatum", "Mikal", "Brunson", "Embiid", "Siakam", "Mitchell", "Ivey", "Tyrese", "Trae", "LaMelo", "Butler", "Banchero", "Porzingis"])
        print(f"Here's the best player on the {team}: {random_eastteam}")
    if search == "bulls":
        print("You are very smart")

search()

# This is a very basic code segment, how can you improve upon this code?

# My improved code is in the segment below.
Chicago Bulls is a team apart of the Eastern Confrence.
Here's the best player on the Chicago Bulls: Tyrese
You are very smart

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 No comment