如何映射到词典

2024-09-28 05:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个清单看起来是这样的:

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

我希望category的所有值都合并到一个键中,然后wordlist中与该类别配对的所有单词都合并到一个列表中。有可能吗?你知道吗

所以最终,有了这个列表,你会看到

['elated', 'happy'], ['elated', 'grateful']

变成:

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

Tags: from列表executeselecthappywordlistcategorysad
2条回答

使用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)
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']}

相关问题 更多 >

    热门问题