Python:将字典与列表中的列表合并为值并对其进行计数 [英] Python: merging dictionaries with lists in lists as values and counting them
问题描述
我正在尝试编写一个可以合并两个字典(TEXT FILES!)的程序.这些词典由名词和动词组成,这些名词和动词已由另一个程序从不同的语料库中索引(然后放入文本文件中).这是这些词典的形式:
I am trying to write a program that can merge two dictionaries (TEXT FILES!). These dictionaries consist of nouns and verbs that have been indexed from different corpora by another program (and then put into a text file). This is the form of these dictionaries:
dict1 = {'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search', 1]]}
dict2 = {'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation': [['receive', 1]], 'mall': [['build', 1]]}
如您所见,它们是带有键的字典,在值列表中具有列表. 现在,我试图获得如下输出:
As you can see, they're dictionaries, with keys, that have lists in lists for values. Now I'm trying to get the output like this:
finaldict = {'strawberry': [['eat', 2]], 'family-member': [['look up', 1]['lose',1]], 'mall': [['search', 1]['build', 1]], 'ovation': [['receive', 1]]
直到现在,我已经能够像这样(以字符串形式)合并dict1和dict2:
Until now, I have been able to merge dict1 and dict2 like this (in a string):
{'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search',
1]], 'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation':
[['receive', 1]], 'mall': [['build', 1]]}
我用下一条语句将此字符串转换为字典: finaldict = eval(str1) 它将整个事情变成一个字典,它也这样说,所以当我询问结局类型时,它不会看到像[['eat',1]]这样的语句作为值或任何东西.我需要这个,所以我可以遍历每个项目并计算该动词出现多少次.
I convert this string as a dictionary with the next statement: finaldict = eval(str1) it turns the whole thing into a dictionary, it also says so when I ask for the type of finaldict, but it won't see the statements like [['eat', 1]] as values or anything. I need this so I can loop over every item and count how many times it appears with which verb.
推荐答案
from collections import Counter
dict1 = {'strawberry': [['eat', 1]], 'family-member': [['look up', 1]], 'mall': [['search', 1]]}
dict2 = {'strawberry': [['eat', 1]], 'family-member': [['lose', 1]], 'ovation': [['receive', 1]], 'mall': [['build', 1]]}
result = {k: Counter(dict(v)) for k, v in dict1.items()}
for k, v in dict2.items():
result.setdefault(k, Counter()).update(dict(v))
result = {k: [list(x) for x in v.items()] for k, v in result.items()}
这篇关于Python:将字典与列表中的列表合并为值并对其进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!