Home > OS >  Python - Reading two files into two dictionaries and comparing keys
Python - Reading two files into two dictionaries and comparing keys

Time:11-11

I have two files, file1.txt and file2.txt, with sets of keys and values. I would need to read both files into two different dictionaries. Thereafter I would loop over both dictionaries in order to:

  1. Check if there are any key duplicates
  2. Check if the value of these key duplicates are at least 8 or above (on a scale from 0 - 10) - if so print them.

The thing I am in doubt about: How to compare keys from two different dictionaries

*I am new to python and learning atm

thanks a lot for any input!

CodePudding user response:

You didn't indicate what you meant by duplicates: 1 Does it mean it exists in the two files. 2 It exists in 2 times in the same file.

For the first scenario, you can read the 2 files to 2 separate dictionnaries. Then run this loop:

for key in file1.keys():
    if key in file2.keys():
        print(key)

For the second scenario, you will need to read the key and values of each file as a list of tuples and loop through them to check for duplicates. Before turning the data into dictionaries

CodePudding user response:

If you are storing dictionaries in a text file, I'd strongly suggest json. You'll find a lot of support in the json module.

For the common keys between two dictionaries, just use set intersection. see https://www.pythontutorial.net/python-basics/python-set-intersection/

d1 = {
    'alpha': 1,
    'beta': 2,
    'gamma': 3,
}

d2 = {
    'alpha': 1,
    'bravo': 2,
    'charlie': 3,
}

common = set(d1.keys()) & set(d2.keys())
print(len(common), common)
  • Related