【问题标题】: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如何构建一个字典,其键和值是包含列表并与列表中的值匹配的列表列表
【发布时间】:2015-12-14 15:25:55
【问题描述】:

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

#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

我无法正确解包。

任何帮助都会很棒。

谢谢。

【问题讨论】:

    标签: dictionary python-3.3 defaultdict


    【解决方案1】:

    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]]]}
    

    【讨论】:

    • 非常感谢,太好了!
    【解决方案2】:

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

    dictList=OrderedDict((k,[]) for k in keyScores)
    
        for k in dataFetch:
            for g in keyScores:
               if k[2] == g:
    
                   dictList[g].append(k)
    

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 2020-03-31
      • 2021-05-14
      相关资源
      最近更新 更多