所以我有一个看起来像这样的列表:
[['hostile', 'angry'], ['elated', 'happy'], ['elated', 'grateful'], ['depressed', 'sad']]
由此产生:
c.execute("""SELECT category, wordlist from wordtest order by category""")
categoryfile = c.fetchall()
categoryfile = [list(x) for x in categoryfile]
我希望将所有类别的值合并为单个键,然后将与该类别配对的wordlist中的所有单词合并为一个列表。这可能吗?
所以最终,有了这个列表,你会看到
['兴高采烈','快乐'],['兴高采烈','感恩']
变成:
{'elated': ['happy', 'grateful']}
答案 0 :(得分:4)
使用collections.defaultdict
:
from collections import defaultdict
myList = [['hostile', 'angry'], ['elated', 'happy'], ['elated', 'grateful'], ['depressed', 'sad']]
myDict = defaultdict(list)
for key, value in myList:
myDict[key].append(value)
答案 1 :(得分:3)
lis=[['hostile', 'angry'], ['elated', 'happy'], ['elated', 'grateful'], ['depressed', 'sad']]
dic={}
for x in lis:
dic.setdefault(x[0],[]).append(x[1])
print dic
<强>输出:强>
{'depressed': ['sad'], 'elated': ['happy', 'grateful'], 'hostile': ['angry']}