如何使用for循环将键和值添加到字典中

时间:2020-10-07 20:16:02

标签: python python-3.x dictionary

所以我收到错误消息: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

1 个答案:

答案 0 :(得分:1)

我假设数据结构是这样的:

['gameX', 'useless_info', 'genreX', 'info', 'info', ...]

我猜想,如果两个列表上的数据结构相同,那么将两个列表加起来并只进行一次交互会更容易吗?

complete_list = list_of_data1 + list_of_data2
    # make one list with all the data
dict_games = {genre : {} for genre in set([x[2] for x in complete_list])}
    # make a dict of dict with all genres

for 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时使用它。请让我知道它是否有效或不清楚。