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 __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?
#
#

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
#
#
{1, 2, 3}

What do you notice in the output?

What we can notice is that the output is a set containing the unique elements of the list [1, 2, 3, 2, 1]. The set data type in Python is an unordered collection of unique elements. When we create a set from a list using the set() function, it automatically removes any duplicates, which is why the output only contains the unique elements 1, 2, and 3.

Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?

Sets are similar to hash tables/hashtables in coding because both are implemented as hash tables in many programming languages, including Python. In a hash table, data is stored in an array-like structure, and the location of each element is determined by its hash value, which is calculated based on its key.

In the case of sets, each element in the set serves as its own key, and the value associated with each key is simply a placeholder value. This is similar to how hash tables work, where each element is stored at a location in the array based on its hash value, and the value associated with that location is the value of the element itself.

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 [square brackets are a list] and dictionaries {curvy brackets are a dictionary}
#

# 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'}}

From the given code snippet, we can see the following data structures:

A dictionary:

lover_album is a dictionary that contains information about the album "Lover" by Taylor Swift.

A list: The value associated with the "genre" key in the lover_album dictionary is a list containing two strings, "Pop" and "Synth-pop". Nested dictionaries:

The value associated with the "tracks" key in the lover_album dictionary is a nested dictionary, where each key-value pair represents a track number and the corresponding song title. Overall, we can see the usage of multiple data structures such as a dictionary, list, and nested dictionary to store and represent information related to the "Lover" album by Taylor Swift.

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?
# Make it a set by adding set and parenthesis 
#

# 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': {'Frank Dukes', 'Louis Bell', 'Taylor Swift', '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? 
# Change tracks to genre and what number genre it is and put "electropop" instead of "All Of The Girls You Loved Before".
# 

# 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': {'Frank Dukes', 'Louis Bell', 'Taylor Swift', 'Jack Antonoff', 'Joel Little'}}
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: {'Frank Dukes', 'Louis Bell', 'Taylor Swift', '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?
# 
#
{'Frank Dukes', 'Louis Bell', 'Taylor Swift', 'Jack Antonoff', 'Joel Little'}

Hacks

  • Answer ALL questions in the code segments
  • Create a venn diagram or other compare and contrast tool related to hashmaps.
    • 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

SavageMode2_album = {
    "title": "Savage Mode II",
    "artist": "21 Savage",
    "year": 2020,
    "genre": ["Rap", "Murder Music"],
    "tracks": {
         1: "Intro",
        2: "Runnin",
        3: "Glock in My Lap",
        4: "Mr. Right Now",
        5: "Rich Nigga Shit",
        6: "Slidin",
        7: "Many Man",
        8: "Snitches & Rats",
        9: "My Dawg",
        10: "Steppin on Niggas",
        11: "Brand New Draco",
        12: "No Opp Left Behind",
        13: "RIP Luv"
    }
}

print(SavageMode2_album)
{'title': 'Savage Mode II', 'artist': '21 Savage', 'year': 2020, 'genre': ['Rap', 'Murder Music'], 'tracks': {1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv'}}
SavageMode2_album = {
    "title": "Savage Mode II",
    "artist": "21 Savage",
    "year": 2020,
    "genre": ["Rap", "Murder Music"],
    "tracks": {
        1: "Intro",
        2: "Runnin",
        3: "Glock in My Lap",
        4: "Mr. Right Now",
        5: "Rich Nigga Shit",
        6: "Slidin",
        7: "Many Man",
        8: "Snitches & Rats",
        9: "My Dawg",
        10: "Steppin on Niggas",
        11: "Brand New Draco",
        12: "No Opp Left Behind",
        13: "RIP Luv"
    },
    "song_lengths": {
        1: "2:12",
        2: "3:16",
        3: "2:59",
        4: "4:08",
        5: "3:07",
        6: "3:09",
        7: "3:09",
        8: "2:56",
        9: "3:27",
        10: "2:27",
        11: "2:59",
        12: "3:05",
        13: "4:13"
    }
}

def get_song_length(song_number):
    return SavageMode2_album["song_lengths"][song_number]

# Example usage
song_number = 5
length = get_song_length(song_number)
print(f"The length of song {song_number} is {length}.")
The length of song 5 is 3:07.
print(SavageMode2_album.get('tracks'))
# or
print(SavageMode2_album['tracks'])
{1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv'}
{1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv'}
print(SavageMode2_album.get('tracks')[3])
# or
print(SavageMode2_album['tracks'][3])
Glock in My Lap
Glock in My Lap
SavageMode2_album["producer"] = set(['Metro Boomin', 'Southside', 'Carlton Mays, Jr.', 'Oz Iskander 40'])
# What can you change to make sure there are no duplicate producers?
# Make it a set by adding set and parenthesis 
#

# Printing the dictionary
print(SavageMode2_album)
{'title': 'Savage Mode II', 'artist': '21 Savage', 'year': 2020, 'genre': ['Rap', 'Murder Music'], 'tracks': {1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv'}, 'song_lengths': {1: '2:12', 2: '3:16', 3: '2:59', 4: '4:08', 5: '3:07', 6: '3:09', 7: '3:09', 8: '2:56', 9: '3:27', 10: '2:27', 11: '2:59', 12: '3:05', 13: '4:13'}, 'producer': {'Southside', 'Metro Boomin', 'Carlton Mays, Jr.', 'Oz Iskander 40'}}
SavageMode2_album["tracks"].update({14: "Said N Done"})

# How would add an additional genre to the dictionary, like electropop? 
# Change tracks to genre and what number genre it is and put "electropop" instead of "All Of The Girls You Loved Before".
# 

# Printing the dictionary
print(SavageMode2_album)
{'title': 'Savage Mode II', 'artist': '21 Savage', 'year': 2020, 'genre': ['Rap', 'Murder Music'], 'tracks': {1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv', 14: 'Said N Done'}, 'song_lengths': {1: '2:12', 2: '3:16', 3: '2:59', 4: '4:08', 5: '3:07', 6: '3:09', 7: '3:09', 8: '2:56', 9: '3:27', 10: '2:27', 11: '2:59', 12: '3:05', 13: '4:13'}, 'producer': {'Southside', 'Metro Boomin', 'Carlton Mays, Jr.', 'Oz Iskander 40'}}
for k,v in SavageMode2_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: Savage Mode II
artist: 21 Savage
year: 2020
genre: ['Rap', 'Murder Music']
tracks: {1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv', 14: 'Said N Done'}
song_lengths: {1: '2:12', 2: '3:16', 3: '2:59', 4: '4:08', 5: '3:07', 6: '3:09', 7: '3:09', 8: '2:56', 9: '3:27', 10: '2:27', 11: '2:59', 12: '3:05', 13: '4:13'}
producer: {'Southside', 'Metro Boomin', 'Carlton Mays, Jr.', 'Oz Iskander 40'}
def search():
    search = input("What would you like to know about the album?")
    if SavageMode2_album.get(search.lower()) == None:
        print("Invalid Search")
    else:
        print(SavageMode2_album.get(search.lower()))

search()

# This is a very basic code segment, how can you improve upon this code?
# 
#
{1: 'Intro', 2: 'Runnin', 3: 'Glock in My Lap', 4: 'Mr. Right Now', 5: 'Rich Nigga Shit', 6: 'Slidin', 7: 'Many Man', 8: 'Snitches & Rats', 9: 'My Dawg', 10: 'Steppin on Niggas', 11: 'Brand New Draco', 12: 'No Opp Left Behind', 13: 'RIP Luv', 14: 'Said N Done'}

Improved Version

Here are a few suggestions for how I improved the code

Use a loop to allow the user to perform multiple searches without exiting the program. This would make the program more user-friendly and efficient.

Include error handling to catch any exceptions that may occur during runtime, such as if the user enters an invalid data type for the search parameter.

Provide more information to the user about what kinds of searches are available, such as a list of valid search terms or a brief explanation of what the program can do.

Consider using a more descriptive variable name than "search" to avoid confusion with the function name and improve readability.

def search_album(album_dict):
    while True:
        search_term = input("What would you like to know about the album? (type 'exit' to quit) ")
        if search_term == 'exit':
            break
        try:
            result = album_dict.get(search_term.lower())
            if result == None:
                print("Invalid search term. Please try again.")
            else:
                print(result)
        except:
            print("An error occurred. Please try again.")
    print("Thanks for using the album search tool!")

# Example usage
SavageMode2_album = {
    'title': 'Savage Mode II',
    'artist': '21 Savage and Metro Boomin',
    'release_date': 'October 2, 2020',
    'recorded': '2020',
    'studio': 'Private studios in Atlanta, Georgia and Los Angeles, California',
    'genre': 'Hip hop, trap',
    'length': '44:07',
    'label': 'Epic, Boominati, Republic',
    'producers': ['Metro Boomin', '21 Savage']
}

search_album(SavageMode2_album)
44:07
Thanks for using the album search tool!
c.execute('''CREATE TABLE IF NOT EXISTS song_opinions 
             (title text, opinion text, rating integer)''')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/var/folders/rb/cg1zlcqx3kd5jwkb_g7zw1980000gn/T/ipykernel_87737/398191197.py in <module>
----> 1 c.execute('''CREATE TABLE IF NOT EXISTS song_opinions 
      2              (title text, opinion text, rating integer)''')

NameError: name 'c' is not defined
import sqlite3

# define the database connection and cursor
conn = sqlite3.connect('song_opinions.db')
c = conn.cursor()

# create a table to store the song opinions if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS song_opinions 
             (title text, opinion text, rating integer)''')

# define a dictionary to store the album information
SavageMode2_album = {
    'title': 'Savage Mode II',
    'artist': '21 Savage & Metro Boomin',
    'year': 2020,
    'tracks': {
        'Intro': 2.36,
        'Runnin': 3.18,
        'Glock in My Lap': 2.41,
        'Mr. Right Now': 4.17,
        'Rich Nigga Shit': 3.05,
        'Slidin': 3.15,
        'Many Men': 3.00,
        'Snitches & Rats (Interlude)': 2.10,
        'Snitches & Rats': 3.22,
        'My Dawg': 3.12,
        'Steppin on Niggas': 2.22,
        'Brand New Draco': 2.57,
        'No Opp Left Behind': 3.06,
        'RIP Luv': 2.47,
        'Said N Done': 3.22
    }
}

# define a function to search for a song and add an opinion and rating
def add_opinion():
    # ask the user for the song title, their opinion, and their rating
    title = input("Enter the title of the song: ")
    opinion = input("Enter your opinion of the song: ")
    rating = int(input("Enter your rating out of 10: "))

    # search for the song in the album
    if title in SavageMode2_album['tracks']:
        # insert the title, opinion, and rating into the database
        c.execute("INSERT INTO song_opinions VALUES (?, ?, ?)", (title, opinion, rating))
        conn.commit()
        print("Opinion added to the database!")
    else:
        print("Song not found in album.")

# call the function to add an opinion
add_opinion()

# close the database connection
conn.close()
Opinion added to the database!
def delete_opinion():
    # define the database connection and cursor
    conn = sqlite3.connect('song_opinions.db')
    c = conn.cursor()
    
    # ask the user for the title of the song to delete
    title = input("Enter the title of the song to delete: ")
    
    # delete the row corresponding to the specified song title
    c.execute("DELETE FROM song_opinions WHERE title=?", (title,))
    conn.commit()
    
    # check if any rows were deleted
    if c.rowcount == 0:
        print("No opinions found for that song title.")
    else:
        print(f"{c.rowcount} opinion(s) deleted from the database.")
    
    # close the database connection
    conn.close()

# call the function to delete an opinion
delete_opinion()
1 opinion(s) deleted from the database.
import webbrowser

song_videos = {
    "My Dawg": "https://www.youtube.com/watch?v=mVIHEE-nxl0",
    "No Heart": "https://www.youtube.com/watch?v=rGxE7jgZvzc",
    "X": "https://www.youtube.com/watch?v=szKxAdvlCCM",
    "Savage Mode": "https://www.youtube.com/watch?v=ztXU2b1v16Y",
    "Bad Guy": "https://www.youtube.com/watch?v=fTbKjLNSFv4",
    "Mad High": "https://www.youtube.com/watch?v=lZhC8NRKzbg",
    "Feel It": "https://www.youtube.com/watch?v=jY0tZXaK1Qg",
    "Ocean Drive": "https://www.youtube.com/watch?v=KHCbBnYVYDc",
    "Savage Mode II": "https://www.youtube.com/watch?v=quO7PekNYp8",
    "Mr. Right Now": "https://www.youtube.com/watch?v=f4RmrWhQxrM",
    "Runnin": "https://www.youtube.com/watch?v=jbdROU6eJVg",
    "Glock in My Lap": "https://www.youtube.com/watch?v=IShUzOqBqOk",
    "Rich N***a Shit": "https://www.youtube.com/watch?v=zlNCU09gzwc",
    "Slidin": "https://www.youtube.com/watch?v=9lVt20ogzoY",
    "Many Men": "https://www.youtube.com/watch?v=-k65rF9yfFc",
    "My Legacy": "https://www.youtube.com/watch?v=gSVfGHx1x7A",
}

song_title = input("Enter the title of a song from Savage Mode II: ")
if song_title in song_videos:
    webbrowser.open(song_videos[song_title])
else:
    print("Song not found.")
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Set up the YouTube Data API client with your API key
api_key = "AIzaSyAD45M4xe1J0MAuPOFdqzYkNY0tCBKOGqU"
youtube = build("youtube", "v3", developerKey=api_key)

# Retrieve the video link for a given song title
def get_video_link(title):
    query = f"{title} 21 Savage Metro Boomin"
    try:
        # Use the YouTube search API to fetch the top result for the query
        search_response = youtube.search().list(
            q=query,
            type="video",
            part="id",
            maxResults=1
        ).execute()

        # Get the video ID from the search response
        video_id = search_response["items"][0]["id"]["videoId"]

        # Construct the video link using the video ID
        video_link = f"https://www.youtube.com/watch?v={video_id}"

        return video_link

    except HttpError as error:
        print(f"An error occurred: {error}")
        return None

# Example usage
song_title = input("Enter a track title: ")
video_link = get_video_link(song_title)

if video_link:
    print(f"The video link for '{song_title}' is {video_link}")
else:
    print(f"'{song_title}' not found on YouTube")
The video link for 'glockk im lapp' is https://www.youtube.com/watch?v=acYUqMd9k2I

yer