Search code examples
dictionarypython-3.3defaultdict

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


I need help building a dictionary which has a key and then values being a list of a list which has a list, in which the keys value matches the third item of list the list and then places it under that key (I will try show by example cause its difficult to word)

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

I was thinking of using defaultdict as expressed in

Python creating a dictionary of lists

I cant get the unpacking right.

Any help would be great.

Thank you.


Solution

  • defaultdict makes it easy to append items to a list without having to check if the key is already present. The parameter to defaultdict is the default item to construct. In this case, an empty list. I also use a set on the keyScores to make to in lookup a little more efficient. pprint just helps pretty print the resulting dictionary.

    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)    
    

    Output:

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