2012-07-13 153 views
1

所以我有一个看起来像这样的列表:通过这个方式如何映射到字典

[['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] 

我希望所有类别的值被合并成单个关键字,然后所有与该类别配对的单词列表中的单词合并为一个列表。那可能吗?

所以,最后,通过这个清单,你会看到,而不是

[ '扬眉吐气', '快乐'],[ '扬眉吐气', '感恩']

转到:

{'elated': ['happy', 'grateful']} 

回答

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) 
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']} 
+0

+1。我喜欢'.setdefault'。 – 2012-07-13 20:40:39