Home > Back-end >  How to convert a file into a list then into a dictionary in python
How to convert a file into a list then into a dictionary in python

Time:10-23

I have a file with each line containing a name and some numbers for instance John, 55 , 77, 89 Sarah, 78, 45, 67 Joe, 40, 99, 63, 89,60 I was able to convert this to a list using split(). But I can’t figure out how to turn it to a dictionary from there. I have something like [‘John’, ‘55,’ ‘77,’… etc. How do I covert this list to a dictionary and am I on the right path?

CodePudding user response:

The quickest way is probably a dict comprehension.

nn_list = ['John', 55 , 77, 89, 'Sarah', 78, 45, 67, 'Joe', 40, 99, 63]
nn_dict = {block[0]:block[1:] for block in (nn_list[i:i 4] for i in range(0,len(nn_list),4))}

CodePudding user response:

You can use the csv module and a dictionary comprehension:

import csv

with open(filename) as f:
    result = {row[0]: row[1:]
              for row in csv.reader(f)}

For each row in the csv file, we build a dictionary using the first value row[0] as the key, and the rest of the the row, row[1:] as the value.

  • Related