PhoenixGirl
PhoenixGirl

Reputation: 21

How to use Python Methods and Instances to store data in a dictionary from a file?

I'm new to python and not very fond of Object oriented programming. I'm trying to figure out the best way to achieve the following:

I want to read a file like this: INPUT from file:

Name,semester,point
abc,5,3.5
cba,2,3.5

I want to store it in a dictionary like the name as a primary key and the other two values it is related to. as in,

OUTPUT maybe:

abc:'5','3.5'

I need to use my stored value for some calculations in other functions. So as long as I store them and can access them in some way it is alright. It can be list, arraylist, dictionary or whatever seems like a good solution.

From what I read, I want to use Methods and Instances instead of class and objects. I think that sounds about right from what I understand.

Please suggest the best way to achieve this, as I have already checked stackoverflow for similar questions and I have only found solutions that are object oriented (which I want to avoid).

Upvotes: 1

Views: 346

Answers (3)

Cereus
Cereus

Reputation: 16

I have used the example by @Ajax1234 above. Seems like a good solution and example.

From what I understand the confusion is between Instances and Classes and their relation to Methods

Methods:

  • A function attached to a class as an attribute is a Method.

Class:

  • They serve as Instance creator factories.
  • Their attributes provide = behaviour data and functions
  • These attributes are inherited by the Instances that are generated from these Classes.

Instances:

  • These represent the concrete items in a program's domain.
  • They inherit their attributes from their class
  • Their attributes record data that vary from object to object.
  • You can only have one instance of a given Method in memory at a time.

For example in a data processing model: programs and records

  • Instances are like the records
  • Classes are like the software that process those data records

Class, Method and Instances explained with Example:

Correct me if I'm wrong in explaining this.

    import sys


    filename = sys.argv[1]

    class Data: # class
        def __init__(self, filename):
            self.data = {} #will store data in empty dictionary
            self.filename = filename

         # funtion in class as attribute can be a METHOD
         def get_data(self): 
            return [i.strip('\n').split(',') for i in open(filename)]

        # funtion in class as attribute can be a METHOD
        def set_data(self):
            for i in self.get_data():
                self.data[i[0]] = i[1:]

    # Instances are derived from Class
    # file_data is an Instance created from the class Data
    file_data = Data(filename)

    # method called through Instance
    file_data.set_data()

    # will print the full dictionary
    print(file_data.data)

Reference: Learning Python by Mark Lutz

Hope this explains it.

Upvotes: 0

Aaditya Ura
Aaditya Ura

Reputation: 12689

One line solution :

print({tuple(i[:1]):i[1:] for i in [i.strip().split(',') for i in open('g.txt')][1:]})
Detailed solution:

final_dict={}

with open("g.txt") as f:
    for i in [i.strip().split(',') for i in f][1:]:

            final_dict[tuple(i[:1])]=i[1:]

print(final_dict)

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

I do not think you need to create a class for this, as the results can be achieved in one line:

Python3 solution:

data = {a:b for a, *b in [i.strip('\n').split(',') for i in open('filename.txt')][1:]}

Python2 solution:

data = {a[0]:a[1:] for a in [i.strip('\n').split(',') for i in open('filename.txt')][1:]}

However, if you were looking for an OO solution:

class Data:
    def __init__(self, filename):
        self.data = {} #will store data in empty dictionary
        self.filename = filename
    def set_data(self):
        for i in self.get_data():
            self.data[i[0]] = i[1:]
    def get_data(self):
        return [i.strip('\n').split(',') for i in open(filename)]
file_data = Data("the_file.txt")
file_data.set_data()
print(file_data.data) #will print the full dictionary

Upvotes: 1

Related Questions