比较两个不同列表中Python中两个字典的值
问题描述:
这是我程序的一小部分,但基本上到目前为止,我已经查看了两个txt文件,并将它们与一个带有关键字的主txt文件进行了比较。对于前两个txt文件(txt文件1 & txt文件2)中的每一个,我从主txt文件中找到单词的频率,并将txt文件的文本和频率放入两个单独的词典中,wordfreq和wordfreq2。比较两个不同列表中Python中两个字典的值
现在我想比较这两个列表中单词的频率。如果wordfreq中的键值比wordfreq2中的键值大,我想将该词添加到anotherdict1中,反之亦然。
anotherdict1 = {}
anotherdict2 = {}
for key in wordfreq.keys():
if key in wordfreq2.keys() > key in wordfreq.keys():
anotherdict2.update(wordfreq2)
for key in wordfreq2.keys():
if key in wordfreq.keys() > key in wordfreq2.keys():
anotherdict1.update(wordfreq)
print (wordfreq)
print (wordfreq2)
答
你在做什么这里正在更新anotherdict2
与wordfreq2
(与同为dict1)。这意味着wordfreq2
中的每个键/值将与anotherdict2
中的相同。但是,您应该做的只是添加特定的键/值对。此外,您的if
检查正在比较两个布尔值。也就是key in wordfreq2.keys()
会导致True或False,而不是值本身。你应该使用wordfreq2[key]
。下面是我该怎么做:
for key, wordfreq_value in wordfreq.items():
wordfreq2_value = wordfreq2[key]
if wordfreq2_value > wordfreq_value:
anotherdict2[key] = wordfreq2_value
else:
anotherdict[key] = wordfreq_value