问题
I have a list like below:
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)]
Now I am performing a basic check to see which pairs have value greater than 0.0 and then append them to a new list like below.
new_words = []
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 x in Lista:
if x[2]>0:
new_words.append(x[1])
My question is how do I append the results in a dictionary with respective key, value pairs. Ideal output required is as below: (Please note earlier new_words was a list but now in the ideal output I want it as a dictionary)
new_words={'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime'],
'alien': ['dell']}
回答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
回答2:
You most likely want a dictionary of lists. Here's one approach using itertools.groupby
:
from itertools import groupby
from operator import itemgetter
{k:[i[1] for i in list(v) if i[2]>0.] for k,v in groupby(Lista, key=itemgetter(0))}
{'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime'],
'alien': ['dell']}
Note: This only works if equal keys are consecutive
回答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
.
来源:https://stackoverflow.com/questions/59287573/how-to-convert-a-list-having-multiple-values-into-a-dictionary-of-lists