Home > Blockchain >  How to input list in a list to a dictionary in Python
How to input list in a list to a dictionary in Python

Time:11-25

To whoever is reading this. I'm having trouble completing an assignment on my first Python course. What I need to do is that I need to create a program, that reads a file which consists of different songs, their genres and their ratings. These info will be in a file by a single line per one stack of information. Like this:

Rap;Gangsta's paradise;88
Pop;7 rings;90
Classic;La Campanella;72
Rap;Still D.R.E;82
Pop;MONTERO;79

In the program I'am excepted to select a good data structure (which is a combination of two simpler data structures), where the data from the file will be saved. By using the data structure what I'm creating, I'm expected to complete different types of functions, which for example are printing out everything and adding new stuff in it etc. etc.

I've chosen to make the data structure, by combining dict and list's, like that there will be a dict created, which keys are the genres and its values are lists of the [songs and their ratings]. (I'm not really sure if that is the wisest way to do this...)

However I'm now having trouble getting my code to the start, because I can't create the data structure properly. As what I've tried I've only resulted in situations, where I can get the dictionary's key value right (genre), but the lists as the dictionary's value cause me trouble.

Here's my code:

def main():
    filename = input("Please, enter the file name: ")

    # Opening the file in try-except bracket. If the file can't be opened, the
    # program prints out an error message and shuts down.
    try:
        file = open(filename, mode="r")

    except OSError:
        print("Error opening the selected file!")
        return
    
    # Defining a dict, where the lists will be inputed.
    dict = {}

    # Going trough each line in the file.
    for line in file:
        # Breaking each line of the file into a list.
        line = line.strip()
        parts = line.split(";")
        # Defining variables for different list values. The values will
        # be in the file in this order.
        genre = parts[0]
        track = parts[1]
        rating = int(parts[2])
        # Inputing each every data in the dict like this:
        # genre is the dict's key and track, rating are the values IN A LIST!
        if genre not in dict:
            dict[genre] = []
        dict[genre].append(track)
        dict[genre].append(rating)
        # The dict now looks like this:
        # {'Rap': ["Gangsta's paradise", 88, 'Still D.R.E', 82], etc.
        # When it should look like this:
        # {'Rap': [["Gangsta's paradise", 88], ['Still D.R.E', 82]], etc.

    # Wrong type values now cause problems in this print section, because
    # I can't print out all possible songs in a specific rating, because I
    # can't go trough the lists properly.
    for genres in dict:
        print(genres.upper())
        print(f"{dict[genres][0]}, rating: {dict[genres][1]}/100")

    file.close()


if __name__ == "__main__":
    main()

In the end I would say, before you even try to help me by formatting my code: Is this the best way to do this, or is there a simplier data structure, which could help me accomplish my task? Thank you very much in advance, it means a lot to me.

CodePudding user response:

This shows storing the track and the rating together in a tuple, and how to iterate through the tuples you collect:

def main():
    filename = input("Please, enter the file name: ")

    # Opening the file in try-except bracket. If the file can't be opened, the
    # program prints out an error message and shuts down.
    try:
        file = open(filename, mode="r")

    except OSError:
        print("Error opening the selected file!")
        return
    
    # Defining a data, where the lists will be inputed.
    data = {}

    # Going trough each line in the file.
    for line in file:
        # Breaking each line of the file into a list.
        line = line.strip()
        parts = line.split(";")
        # Defining variables for different list values. The values will
        # be in the file in this order.
        genre = parts[0]
        track = parts[1]
        rating = int(parts[2])
        if genre not in data:
            data[genre] = []
        data[genre].append((track,rating))

    for genre,tunes  in data.items():
        print(genre.upper())
        for tune in tunes:
            print(f"{tune[0]}, rating: {tune[1]}/100")

    file.close()

if __name__ == "__main__":
    main()
  • Related