Skip to content Skip to sidebar Skip to footer

How To Filter A List Of Tuples By Items At Given Index And Convert Them Into A Dictionary Of Lists

I have a list like below: Lista = [('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7),

Solution 1:

You can't have the desired result in a dictionary as dictionaries don't contain duplicate keys (similar to a normal English dictionary: where the words might spell the same but there are differences in pronunciation).

The desired result can be stored again into a list.

newDict = {}
result = []

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

for items in Lista:
    if items[2] > 0.0:
        newDict[items[0]] = items[1]
        result.append(newDict)
        newDict = {}

print result

Solution 2:

You most likely want a dictionary of lists. Here's one approach using itertools.groupby:

from itertools import groupby
fromoperator import itemgetter

{k:[i[1] for i inlist(v) if i[2]>0.] for k,v ingroupby(Lista, key=itemgetter(0))}

{'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime'],
 'alien': ['dell']}

Note: This only works if equal keys are consecutive

Solution 3:

You could use a defaultdict:

from collections import defaultdict

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

dct = defaultdict(list)

for item in Lista:
    key, value, score = item
    if score > 0.0:
        dct[key].append(value)

print(dct)

Which yields

defaultdict(<type'list'>, {
    'alien': ['dell'], 
    'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime']
})

Your initial request - having a dictionary with multiple identical keys - is not possible in Python.

Post a Comment for "How To Filter A List Of Tuples By Items At Given Index And Convert Them Into A Dictionary Of Lists"