warbirdn warbirdn - 4 months ago 7
Python Question

Trying to Compare a dictionary to a text file

I am trying out python for a simple web scrapper that checks a website for names, puts them all in a dictionary with the link, then compares the names to a list I all ready have saved. The problem I am stuck on is trying to make a new dictionary with the names from the website that are not in the saved list.

together = dict(zip(names, links))
final_dict = {}


for k, v in together.items():
with open('file.txt', 'r') as f:
file_lines = f.readlines()
if k in file_lines:
print('All ready have that name.')
pass
else:
print(k, v)
final_dict.update({k, v})
f.close()


The saved file only has the
k
value of the
together
dictionary.

Answer

Try to change

file_lines = f.readlines()

to

file_lines = f.read().splitlines()  

The former one keeps the newline \n at the end of the line.

In addition final_dict.update({k, v}) should probably be final_dict.update({k: v}) and as others already pointed out, you may have an issue with your indentation.

Comments