Home > Mobile >  Error in returning dictionary items as string? (python)
Error in returning dictionary items as string? (python)

Time:12-10

I have a class that has an empty dictionary attribute:

class Library:
    def __init__(self,library):
        self.library={}
    
    def addSong(self,title,artist,genre,playCount):
        for i in self.library.keys():
            if i == title:
                x=self.library.get(title)
                x[2]= x[2] 1
            else:    
                self.library[title]=[artist,genre,playCount]
    
    def song2String(self,title):
        x=self.library.get(title)
        return f"{x[0]} {title} ({x[1]}), {x[2]}" 

Now when I do this:

m1= Library({})
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)

The code runs properly and items are added to the m1 dictionary. But when I type this:

print(m1.song2String("Saturday Night's Alright for Fighting"))

I get this error message:

return f"str{x[0]} str{title} (str{x[1]}), str{x[2]}" 
TypeError: 'NoneType' object is not subscriptable

What is my syntax error?

CodePudding user response:

You iterate on the library keys : for i in self.library.keys(), but as there is none, nothing is done, the minimal change to make it work is

def addSong(self, title, artist, genre, playCount):
    for i in self.library.keys():
        if i == title:
            x = self.library.get(title)
            x[2] = x[2]   1
            break
    else:
        self.library[title] = [artist, genre, playCount]

But the best is just to test if the title is present, then do the right thing.

def addSong(self, title, artist, genre, playCount):
    if title in self.library:
        self.library[title][2]  = playCount
    else:
        self.library[title] = [artist, genre, playCount]

CodePudding user response:

Your current code return None, this is the cause of your error. I am not sure why you looped over the keys to insert your song, just use the dictionary directly:

class Library:
    def __init__(self,library):
        self.library={}
    
    def addSong(self,title,artist,genre,playCount):
        if title in self.library:   ## changed code here and below
            x=self.library.get(title)
            x[2]= x[2] 1
        else:    
            self.library[title]=[artist,genre,playCount]
    
    def song2String(self,title):
        x=self.library.get(title)
        return f"{x[0]} {title} ({x[1]}), {x[2]}" 

output:

m1= Library({})
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
print(m1.library)
# {"Saturday Night's Alright for Fighting": ['Elton John', 'Rock', 22]}

print(m1.song2String("Saturday Night's Alright for Fighting"))
# Elton John Saturday Night's Alright for Fighting (Rock), 22

CodePudding user response:

I Suppose this is what you expected. In here In addsong function, first I check is any keys available the dictionary. If it is true, iterate and do what you want. otherwise, add the first dictionary item to the dictionary. Inside the songs2string method, first you want to identify how a dictionary works. In this case, key is a string and the value is list in the dictionary. So then You can return what you want using a dictionary.

class Library:
    def __init__(self,library=dict()):
        self.library=library
    
    def addSong(self,title,artist,genre,playCount):
        
        if len(self.library.keys())>0:
            for i in self.library.keys():
                if i == title:
                    x=self.library.get(title)
                    x[2]= x[2] 1
        else:    
            self.library[title]=[artist,genre,playCount]
            # print(self.library)
    
    def song2String(self,title):
        x=self.library
        print(x)
        return x[title][0], x[title][1], x[title][2]
    
m1= Library()
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
print(m1.song2String("Saturday Night's Alright for Fighting"))
  • Related