File, delete each row and add to the key in the dictionary

advertisements

How do we split the first line in a text file and make them as keys, and every line after that are the values for each key. Without any imports

What I have so far:

new_dict = {}
with open(file, 'r') as f:
    for line in f:
        list = line.strip().split(',')
        for item in list:
            new_dict[item] = []

what this outputs: {'name': [], 'last': [], 'middle': []}

Now, how do I move on to the next line, split at the comma and append the first element to the first key, the second element to the second key, etc.

file:
name, last, middle
bob, jones, m
jones, bob, k
alice, lol, f

Result in the end:

{'name': ['bob', 'jones', 'alice'], 'last': ['jones', 'bob', 'lol'], 'middle': ['m', 'k', 'f']}


new_dict = {}
names = [] # used map 0, 1, 2 to `name`, `last`, `middle`
with open('/path/to/test.txt') as f:

    # Handle header (the first) line: `name, last, middle`
    for name in next(f).split(','): # split fields by `,`
        name = name.strip()  # remove surrounding spaces
        names.append(name)
        new_dict[name] = []  # initialize dictionary with empty list.

    # Handle body.
    for line in f:
        # enumerate(['bob', 'jones', 'm']) return an interator
        #    that generates (0, 'bob'), (1, 'jones'), (2, 'm')
        for i, value in enumerate(line.split(',')):
            new_dict[names[i]].append(value.strip())

print(new_dict)

output:

{'middle': ['m', 'k', 'f'], 'last': ['jones', 'bob', 'lol'], 'name': ['bob', 'jones', 'alice']}