You are given a file called data.txt. Each line in this file contains a name and an email address separated by a comma. However, some of the lines are corrupted and might have more than one comma or might be missing an email or a name. Your task is to write a function that parses this file, filters out the corrupted lines, and returns a dictionary where names are keys and email addresses are values.
The output dictionary should have all the names in lowercase and sorted based on the names.
For example, If data.txt contains:
John Doe,johndoe@example.com
Alice,alice@example.com
Malformed Data,anotherdata,extra@gmail.com
Bob Smith
Eve,eve@example.com
Your function should return:
{
'alice': 'alice@example.com',
'eve': 'eve@example.com',
'john doe': 'johndoe@example.com'
}
What I have tried:
def parse_data(filename):
result = {}
with open(filename, 'r') as file:
lines = file.readlines()
for line in lines:
parts = line.strip().split(',')
return result
This is all I got at the moment. The function parse_data is supposed to open a file and read its content line by line. Each line is split using the comma as a delimiter. I need to complete the function such that it:
1. Checks if the line is valid (i.e., it has exactly two parts: a name and an email).
2. Adds valid data to the result dictionary.
3. Sorts the dictionary based on names.
However, I am not sure where to of what to start with in the for loop. May I please get some hints?