Comparing the keys of one dictionary with the values of another

Question:

So, I have two dictionaries. Both are created from a txt-file with different Documents.
The first dictionary has as its keys the Document-Id and as the corresponding value the document itself.
The second dictionary has as keys every word of all the documents and as value a 1.
I want increase the value of every key in the second dictionary by 1, everytime a word comes up inside the values of a key of Dictionary one that matches a key in the second dictionary.
As an example:

dict1 = {'Doc-Id1' : ['It', 'was', 'summertime'], 'Doc-Id2' : ['It', 'is', 'night', 'o', 'dark', 'night']}
dict2 = {'It' : 1, 'was' : 1, 'summertime' : 1, 'is' : 1, 'night': 1, 'o' : 1, 'dark': 1}

should change to



dict2 = {'It' : 2, 'was' : 1, 'summertime' : 1, 'is' : 1, 'night': 2,'o' : 1, 'dark': 1}

as the "It" and "night" can be found two times in dict1.

Can somebody help me out here? I dont have any idea, how to accomplish this task

I tried some comprehensions but I cant find any why to compare the keys of one dictionary with the values of another.

Asked By: user11579493

||

Answers:

The following program works like described:

dict1 = {'Doc-Id1' : ['It', 'was', 'summertime'], 'Doc-Id2' : ['It', 'is', 'night', 'o', 'dark', 'night']}
dict2 = {'It' : 1, 'was' : 1, 'summertime' : 1, 'is' : 1, 'night': 1, 'o' : 1, 'dark': 1}

for v in dict1.values():
    for w in v:
        dict2[w] += 1

But the values are different (you have 2 "It", then the "It" value is increment twice from 1, which makes 3 not 2).

This program needs the dict2to contains all the needs words (else a key error is raised).

If you want to proceed with extra words:

for v in dict1.values():
    for w in v:
        try:
            dict2[w] += 1
        except KeyError:
            dict2[w] = 1
Answered By: Frédéric LOYER
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.