Home > Software design >  how to print a list that is in a dictionary, as a string in python? And how to edit the list's
how to print a list that is in a dictionary, as a string in python? And how to edit the list's

Time:12-13

I have a class that has a dictionary attribute. The dictionary has song titles as its key and a list containing artist, genre and playCount like this:

class library:
def __init__(self,library):
    self.library={}
def addSong(self,title,artist,genre,playCount):
    self.library[title]=[artist,genre,playCount]

The playCount is an integer. How do I add a 1 to the playCount element without changing any of the other elements. Do I make a new function for it or can I do it without making a function?. Also how can I make a function to print the keys and values of the dictionary as a string like this:

artist, title (genre), playCount

CodePudding user response:

IIUC, you just want to increment playCount every time you pass an existing title to addSong, right?

You can put in an if-else condition in addSong to check if title is in self.library or not and if it exists, then just increment the last element of value of key title by playCount.

Also, to print, it's just a matter of assigning items in their correct positions:

class library:
    def __init__(self):
        self.library = {}
    
    def addSong(self, title, artist, genre, playCount=1):
        if title in self.library:
            self.library[title][-1]  = playCount
        else:
            self.library[title] = [artist, genre, playCount]
            
    def get_song_data(self, title):
        if title in self.library:
            x = self.library[title]   [title]
            return "{0}, {3} ({1}), {2}".format(*x)

lib = library()

Output:

lib.addSong('Easy on Me','Adele','ballad',10)
print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 10

lib.addSong('Easy on Me','Adele','ballad',2)
print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 12

lib.addSong('Easy on Me','Adele','ballad')
print(lib.get_song_data('Easy on Me'))         # Adele, Easy on Me (ballad), 13
  • Related