2012-07-13 200 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