Home > Back-end >  How can I read from this file and turn it to a dictionary?
How can I read from this file and turn it to a dictionary?

Time:01-01

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

CodePudding user response:

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:]

CodePudding user response:

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)
    }
  • Related