I'm new at Python and am stuck with this task.
I have a file with several lists of dicts, but only one list has all keys spelled correctly. I need to find it and print which is correct before I move to the second task, where I'm gonna use the correct list.
Example of the lists:
list_1 = [{'first_key': 'random value', 'second_key': 'random value', 'third_key': 'random value'}]
list_2 = [{'first_key': 'random value', 'sscond_key': 'random value', 'third_key': 'random value'}]
list_3 = [{'first_keet': 'random value', 'second_key': 'random value', 'third_key': 'random value'}]`
I've created a class with one method meant to for-loop through the lists of dicts, looking something like this:
from my_file import list_1, list_2, list_3
class MyClass:
def __init__(self, my_file, something):
self.my_file = my_file
self.something = something
def is_key_present(self):
for x in self.my_file:
if self.something in x is True:
continue
else:
return False
return
Now, I need to create a second method to find which list has only the right spelled keys and then print the result.
I'm fairly confident that my first method is correct, but the second one I've no clue how to set up.
I've tried something like this:
def check_for_keys(self):
check_first_key = self.is_key_present(self.something == 'first_key')
check_second_key = self.is_key_present(self.something == 'second_key')
check_third_key = self.is_key_present(self.something == 'third_key')
first_checker = MyClass(my_file = list_1)
first_checker.check_for_keys()
But when I try to call the class I get an error saying
first_checker = MyClass(my_file = list_1)
TypeError: MyClass.__init__() missing 1 required positional argument: 'something'
I tried adding a for loop in the second method looking something like this:
for check_first, check_second, check_third in zip(list_1, list_2, list_3):
if self.something in check_first or check_second or check_third is True:
print(f'list is ok')
else:
print(f'list is not ok')
print(check_email)
print(check_model)
print(check_purchase_date)
But I get the same error message as mentioned previously.
CodePudding user response:
You should post a sample of your file.
But then I'd something much simpler, for every line of the file, try to json decode it, and if it works the list of object is valid.
import json
with open('file.txt') as f:
for line in f:
try:
json.decode(line)
print('valid object', line)
except json.decoder.JSONDecodeError as e:
print('invalid object')
continue
CodePudding user response:
Your code has the init() set up with three parameters, none of which have defaults. So as a result, you need to always pass in the file and something arguments.