如何构建一个字典,其键和值是包含列表并与列表中的值匹配的列表列表

How to build a dictionary with a key and value being a list of list containing a list and matched to a value within a list

我需要帮助构建一个字典,它有一个键,然后是一个列表的列表,该列表有一个列表,其中键值与列表的第三项匹配,然后将它放在该键下 (我会尝试通过示例展示,因为它很难表达)

#This is the score users achieve and needs to be the keys of the dictionary)
keyScores = [5,4,3,2,1]


# The data represents at [0] =user_id , [1] = variables for matching,[2] = scores  
#      (if its score == to a dictionary key then place it there as a value )

fetchData = [
             [141, [30, 26, 7, 25, 35, 20, 7], 5], 
             [161, [36, 13, 29], 5], 
             [166, [15, 11, 25, 7, 34, 28, 17, 28],3]
            ]


#I need to build a dictionary like this:

    {5: [[141, [30, 26, 7, 25, 35, 20, 7],[161, [36, 13, 29]], 
     3:[[166, [15, 11, 25, 7, 34, 28, 17, 28]
     }

我正在考虑使用

中表达的 defaultdict

Python creating a dictionary of lists

我无法正确打开包装。

任何帮助都会很棒。

谢谢。

可能不是最好的方法,但这对我有用:

dictList=OrderedDict((k,[]) for k in keyScores)

    for k in dataFetch:
        for g in keyScores:
           if k[2] == g:

               dictList[g].append(k)

defaultdict 可以轻松地将项目附加到列表中,而无需检查键是否已经存在。 defaultdict 的参数是要构造的默认项。在本例中,是一个空列表。我还在 keyScores 上使用 set 来提高 in 查找的效率。 pprint 只是帮助漂亮地打印生成的字典。

from collections import defaultdict
from pprint import pprint

D = defaultdict(list)
keyScores = set([5,4,3,2,1])
fetchData = [
             [141, [30, 26, 7, 25, 35, 20, 7], 5], 
             [161, [36, 13, 29], 5], 
             [166, [15, 11, 25, 7, 34, 28, 17, 28],3]
            ]
for id,data,score in fetchData:
    if score in keyScores:
        D[score].append([id,data])
pprint(D)    

输出:

{3: [[166, [15, 11, 25, 7, 34, 28, 17, 28]]],
 5: [[141, [30, 26, 7, 25, 35, 20, 7]], [161, [36, 13, 29]]]}