How can I read from this file and turn it to a dictionary?

Question:

I’ve tried several methods to read from this file and turn it to a dictionary but I’m having a lot of errors

I’ve tried the following method but it did not work I got not enough values unpack.

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

I want to read and convert it to this:

{123: ['Ahmed Rashed', 'a', '1000.0'], 456: ['Noof Khaled', 'c', '0.0'], 777: ['Ali Mahmood', 'a', '4500.0']}

File

Asked By: Sul6an

||

Answers:

Split on commas instead.

d = {}
with open("file.txt") as f:
     for line in f:
         parts = line.rstrip('n').split(',')
         d[int(parts[0])] = parts[1:]
Answered By: Unmitigated

Using csv.reader to read the file and split it into its fields:

import csv
with open("file.txt") as f:
    d = {
        int(num): data
        for num, *data in csv.reader(f)
    }
Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.