从类python中的文件构建字典

时间:2014-04-10 23:17:41

标签: python class

我正在尝试构建一个类,该类从一个文件构建一个字典,该文件接受列表中的第一个项目并使其成为键值,列表值中的其余项目。所以最后我称之为

neighbors=Neighbors(FileName.txt)

但是当我说

neighbors['New York']

它不会返回该键的值

class Neighbors(dict):

def __init__(self, fname):
    states=[]
    states1=[]
    states2=[]
    self.fname=open(fname)
    for line in self.fname:
        line=line[:-1]
        states.append(line)
    for line in states:
        states1.append(line.split(','))
    for line in states1:
         item=[x.strip(' ') for x in line]
         states2.append(item)
    a=dict([(t[0],t[1:]) for t in states2])

neighbors = Neighbors("us_states_adjacency.txt")
print neighbors

1 个答案:

答案 0 :(得分:1)

def neighbors(fname):
    def make_line(adjacent_cities):
        line = [city.strip() for city in adjacent_cities.split(",")]
        return line[0],line[1:]
    return dict(map(make_line,open(fname)))

我是怎么做到的,我想...

没有理由为此使用类......你只需要一本字典

然而,如果你真的希望它成为一个班级

class Neighbors(dict):
     def __init__(self,fname):
         def make_line(adjacent_cities):
              line = [city.strip() for city in adjacent_cities.split(",")]
              return line[0],line[1:]
         dict.__init__(self,map(make_line,open(fname)))

如果你不想推动你原来的课程,你只想修复它,你只需要调用super inits方法

class Neighbors(dict):

    def __init__(self, fname):
        states=[]
        states1=[]
        states2=[]
        self.fname=open(fname)
        for line in self.fname:
            line=line[:-1]
            states.append(line)
        for line in states:
            states1.append(line.split(','))
        for line in states1:
             item=[x.strip(' ') for x in line]
             states2.append(item)
        dict.__init__(self,[(t[0],t[1:]) for t in states2]) # call super constructor on our dict ...

这是一个更简单的类,它会覆盖dict ...

class dummy(dict):
  def __init__(self,initializer):
      dict.__init__(self,initializer)

d = dummy([('a',2),('b',4)])
print d['a']
print d['c']