Home > database >  How to read two files into a dict and print specific values
How to read two files into a dict and print specific values

Time:11-15

So, I am learning python and have these fun assignments

I have two files rating_strikers1.txt and rating_strikers2.txt where they have rated some football strikers from 1 to 99.

The textfile rating_strikers1 has this in it:

Kane ; 85

Aubameyang ; 80

Werner ; 76

Lukaku ; 88

The textfile "rating_strikers2" has this in it:

Kane ; 85

Aubameyang ; 80

Werner ; 76

Lukaku ; 88

Lacazette ; 75

Antonio ; 80

I have to read these files into a dict and check if a key is also in the other file. However, I also need to only print out ratings that are 80 or more.

I want to define a function that reads the file and returns a dict.

expected output: print out all the strikers that 'rating_strikers1.txt' and 'rating_strikers2.txt' both rated with 80 or more.

CodePudding user response:

try this:

def myfunc():
     files = list()
     files.append(open('rating_strikers1.txt', 'r'))
     files.append(open('rating_strikers2.txt', 'r'))
     outdict = dict()

     for file in files:
          for line in file.read().splitlines():
               try:
                    key, value = line.split(" ; ")
                    if key not in outdict.keys():
                         outdict[key] = list()
                    outdict[key].append(int(value))
               except:
                    pass

     
     for key, value in outdict.items():
          if all(x >= 80 for x in value):
               print(key, value)

myfunc()
  • Related