为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

阿晨1998 2023-10-18 16:32:21
所以我收到错误: 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 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

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


['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 时使用它。请告诉我它是否有效或者是否有什么不太清楚。


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信