从文件中返回字典

时间:2016-10-13 02:48:40

标签: file class dictionary python-3.4

我已经编写了这个定义类

的代码
class OrderRecord:
"""Defines an OrderRecord class, suitable for use in keeping track of order records"""
    import tools2
    def __init__(self, string):
        """Creates a new OrderRecord object"""
        string = string.split(',')
        self.date = string[0]
        self.location = string[1]
        self.name = string[2]
        self.colour = string[3]
        self.order_num = string[4]
        self.cost = 0


    def cost_of_order(self):
        """Creates a list of the name and adds up the cost of each letter"""
        letter = list(self.name)
        for let in letter:
            self.cost = self.cost + self.tools2.letter_price(let, self.colour)
        return self.cost


    def __str__(self):
        """Calls the cost_of_order function and returns the split string in the required format"""
        self.cost = self.cost_of_order()
        return("Date:      {0}\nLocation:  {1}\nName:      {2}\nColour:    \
    {3}\nOrder Num: {4}\nCost:      {5:.2f}".format(self.date, self.location, \
    self.name, self.colour, self.order_num, self.cost))

现在我需要编写一个函数来读取包含以下内容的文件:

20130902,Te Rakipaewhenua,Vinas,parauri,8638
20130909,Te Papaioea,McClary,kikorangi,11643
20131215,Kapiti,Labrie,kikorangi,65291
20141106,Waihopai,Labrie,ma,57910

并返回一个字典,该字典将该位置作为键,并将OrderRecords列表作为值。

我知道这不是一项艰巨的任务,但我已经坚持了一段时间,因为我无法理解为此做些什么。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许是这样的。它不是解决方案,但它有你需要的一些修改。

import collections    

dct_result = collections.defaultdict(list)
for line in open('file_path'):
    fields = line.split(',')
    # index 1 being the second column
    dct_result[field(1)].append(OrderRecord( some args ))