如何使用键和值构建字典,该列表包含列表并与列表中的值匹配

时间:2015-12-14 15:25:55

标签: dictionary python-3.3 defaultdict

我需要帮助构建一个字典,该字典有一个键,然后值是列表的列表,列表中有一个列表,其中键值匹配列表的第三项列表,然后将其放在该键下 (我会尝试通过示例来表示难以言语)

#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

我无法解开包装。

任何帮助都会很棒。

谢谢。

2 个答案:

答案 0 :(得分:0)

问题不是最好的方法,但这对我有用:

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

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

               dictList[g].append(k)

答案 1 :(得分:0)

defaultdict可以轻松地将项目附加到列表中,而无需检查密钥是否已存在。 defaultdict的参数是要构造的默认项。在这种情况下,一个空列表。我还使用set上的keyScores使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]]]}