Multiple column text file to dictionary..

Submitted 3 years, 7 months ago
Ticket #122
Views 247
Language/Framework Python
Priority Medium
Status Closed

A file having number of rows and columns where the input file are not fixed. Also,  there can be duplicate valid points. The format of the input file looks like the following:

Point Sample1_X_Coordinate Sample1_Y_Coordinate Sample2_X_Coordinate Sample2_Y_Coordinate and so on

A 20 10 18 9

B 16 13 15 13

A 21 11 19 9

C 8 5 8 4

want to store these files  like the following for doing additional manipulations (adding pseudocode )

outputdata[this_sample][this_point].append((this_sample_point_X_coordinate, this_sample_point_Y_coordinate))

i.e, the data to be stored in the following way:

outputdata[Sample1][A] = list[(20,10), (21,11)]

outputdata[Sample2][A] = list[(18,9), (19,9)]

How to implement the above in python?

Thanks!

Submitted on Sep 10, 20
add a comment

2 Answers

Verified

import csv
from pprint import pprint

class ListDict(dict):
    """ Dictionary who's values are lists. """
    def __missing__(self, key):
        value = self[key] = []
        return value

filename = 'multi_col.csv'

lstdct = ListDict()
with open(filename, 'rb') as csvfile:
    for row in csv.reader(csvfile, delimiter='|'):
        key, value = row[:2]
        lstdct[key].append(value)

Submitted 3 years, 6 months ago

import csv
from pprint import pprint

class ListDict(dict):
    """ Dictionary who's values are lists. """
    def __missing__(self, key):
        value = self[key] = []
        return value

filename = 'multi_col.csv'

lstdct = ListDict()
with open(filename, 'rb') as csvfile:
    for row in csv.reader(csvfile, delimiter='|'):
        key, value = row[:2]
        lstdct[key].append(value)

Submitted 3 years, 6 months ago


Latest Blogs