如何将列表中的列表输入 Python 中的字典

How to input list in a list to a dictionary in Python

致所有正在阅读本文的人。我在完成第一门 Python 课程的作业时遇到问题。我需要做的是我需要创建一个程序,读取一个包含不同歌曲、它们的流派和评级的文件。这些信息将在一个文件中,每一堆信息一行一行。 像这样:

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

在程序中,我被排除在select 一个好的数据结构(它是两个更简单的数据结构的组合)中,其中将保存文件中的数据。通过使用我正在创建的数据结构,我有望完成不同类型的功能,例如打印出所有内容并在其中添加新内容等。

我选择通过组合字典和列表来制作数据结构,这样就会创建一个字典,其中键是流派,它的值是 [歌曲及其评级] 的列表。 (我不确定这是否是最明智的做法...)

但是,我现在无法开始编写代码,因为我无法正确创建数据结构。正如我所尝试的那样,我只导致了这样的情况,我可以正确地获得字典的键值(流派),但是作为字典值的列表给我带来了麻烦。

这是我的代码:

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()

最后我想说的是,在您尝试通过格式化我的代码来帮助我之前:这是最好的方法吗,还是有更简单的数据结构可以帮助我完成我的任务?非常感谢你,这对我来说意义重大。

这显示了将曲目和评分一起存储在一个元组中,以及如何循环访问您收集的元组:

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()