如何使用 for 循环向字典添加键和值

所以我收到错误: RuntimeError:字典在迭代期间更改了大小。


我有 2 个矩阵,一个用于 Xbox 信息,一个用于 PS4 信息 第一个函数根据 Xbox 矩阵创建字典。它查看矩阵内的每个列表,并从每个列表中获取信息并将其添加到字典中。第二个函数获取已经制作的字典 def create_dictionary_xbox并添加到其中。我正在尝试使其打印出如下内容:


{genre:{game:[info], game:[info]}}

这是我的代码:


def create_dictionary_xbox(lists_of_data):

    dictionary = {}

    for list_ in lists_of_data:

        game = list_[0]

        genre = list_[2]


        if genre not in dictionary:

            dictionary[genre] = {game : list_[3:]}

        elif genre in dictionary:

            (dictionary[genre])[game] = list_[3:]

            

    return dictionary

        

def create_dictionary_PS4(lists_of_data,dictionary):

    for list_ in lists_of_data:

        game = list_[0]

        genre = list_[2]


        for key in dictionary:

            if genre not in dictionary:

                dictionary[genre] = {game : list_[3:]}

            elif genre in dictionary:

                (dictionary[genre])[game] = list_[3:]


    return dictionary


阿晨1998
浏览 72回答 1
1回答

子衿沉夜

我假设数据结构是这样的:['gameX', 'useless_info', 'genreX', 'info', 'info', ...]我想如果两个列表上的数据结构相同,那么将两个列表相加并仅交互一次会更容易,对吧?complete_list = list_of_data1 + list_of_data2    # make one list with all the datadict_games = {genre : {} for genre in set([x[2] for x in complete_list])}    # make a dict of dict with all genresfor game, _, genre, *info in complete_list:    if game in dict_games[genre]:        # check if the game exits on both list of data and sum the info        info = info + dict_games[genre][game]    dict_games[genre].update({game: info})如果您想对两个列表中出现的同一游戏的信息进行求和,我认为这是最简单的方法。但如果你想丢弃信息,那么你可以按优先级对数据列表求和,或者如果你想创建一些规则来丢弃信息,那么我建议在数据结构上附加一个标志,并在稍后更新 dict_games 时使用它。请告诉我它是否有效或者是否有什么不太清楚。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python