0

I'm struggling to read lines in from a CSV and sort them into multiple different dictionaries.

ABW,Latin America & Caribbean,High income,Aruba

Are four example values in each line of the CSV. I want Aruba to be the key with the preceding three saved as a list for the dictionary value.

with open(filename, mode='r') as csv_file:
            line_count = 0
            for line in csv.DictReader(csv_file, ("country code", "region", "income", "name")):
                print(line)

I'm not sure how to use DictReader to achieve this goal. The above code correctly sorts everything into those keys but I'm not sure how else to specify what value ends up they key and what value goes into the list.

Aruba: ['ABW','Latin America & Caribbean','High income']

That is how I want it to end up looking.

3 Answers3

0

You can do this:

  1. Create an empty dict your_data={};
  2. Read the line using csv.reader, which returns a list of data items in a line as row;
  3. create the entry into your dict with your_data[row[-1]]=row[0:-1].

So, something like this (untested...):

with open(filename, mode='r') as csv_file:
            line_count = 0
            your_data={}
            reader=csv.reader(csv_file)
            for row in reader:
                your_data[row[-1]]=row[0:-1]
dawg
  • 98,345
  • 23
  • 131
  • 206
0

You can do it easily by using pandas with such as: (this is inspirés from Convert a Pandas DataFrame to a dictionary )

import pandas as pd
#header and names args depend of your csv file
df=pd.read_csv(filename, header=0,names=["country code", "region", "income", "name"] 
  

dico=df.set_index('name').T.to_dict('list')
Renaud
  • 2,709
  • 2
  • 9
  • 24
0

This would be one way to achieve what you are looking for

dic = {}
with open('csvfile1.csv', mode='r') as csv_file:
            for line in csv_file:
                line = line.rstrip().split(',')
                dic[line[-1:][0]] = line[:-1]
Mitchell Olislagers
  • 1,758
  • 1
  • 4
  • 10