Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较python中两个不同列表中的两个字典中的值_Python_Python 3.x_Dictionary - Fatal编程技术网

比较python中两个不同列表中的两个字典中的值

比较python中两个不同列表中的两个字典中的值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,这是我程序的一小部分,但基本上到目前为止,我已经浏览了两个txt文件,并将它们与一个带有关键字的主txt文件进行了比较。对于前两个txt文件(txt文件1和txt文件2),我从主txt文件中找到了单词的频率,并将txt文件1和txt文件2的单词及其频率放入两个单独的词典wordfreq和wordfreq2中 现在我想比较这两个列表中单词的频率。如果wordfreq中的某个键的值大于wordfreq2中的同一个键的值,我想将该词添加到另一个dict1中,反之亦然 anotherdict1 = {}

这是我程序的一小部分,但基本上到目前为止,我已经浏览了两个txt文件,并将它们与一个带有关键字的主txt文件进行了比较。对于前两个txt文件(txt文件1和txt文件2),我从主txt文件中找到了单词的频率,并将txt文件1和txt文件2的单词及其频率放入两个单独的词典wordfreq和wordfreq2中

现在我想比较这两个列表中单词的频率。如果wordfreq中的某个键的值大于wordfreq2中的同一个键的值,我想将该词添加到另一个dict1中,反之亦然

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)

您在这里所做的是使用
wordfreq2
更新另一个dict2(dict1也是如此)。这意味着
wordfreq2
中的每个键/值在
另一个dict2
中都是相同的。然而,您应该做的只是添加特定的键/值对。此外,您的
if
检查正在比较两个布尔值。也就是说,
输入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