Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing the keys of one dictionary with the values of another

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading