Python - 将文件读取到字典

时间:2018-01-13 18:06:54

标签: python dictionary file-io

我有一个.txt文件,如下所示:

Key1    Key2    Key3
Val1-A  Val2-A  Val3-A
Val1-B  Val2-B  Val3-B
....

每个字段由制表符分隔,如何在不使用任何for / while循环的情况下读取文件并将其存储在列表字典中?允许理解

with open("file.txt", "r") as input:
    #comprehension here

谢谢!

编辑:抱歉,我忘了包括我到目前为止的尝试

 try:
    with open("file.txt", "r") as input:
        line = input.readline()
        line = re.split(r '\t+', line)
        myDict = dict(line.strip() for line in infile)
        if line == "":
            raise ValueError            
 except IOError:
    print ("Error! File is not found.")
 except ValueError:
    print("Error! File is empty.")

2 个答案:

答案 0 :(得分:2)

检查一下:

var Test = (function() {
  var objects = [];
  var InnerObject = {
    init: function(data) {
      this.prop1 = data.prop1 || 'first';
      this.prop2 = data.prop2 || 'second';
      this.prop3 = data.prop3 || 'third';
      return this;
    }
  };
  return {
    init: function(data) {
      data.forEach(function (item) {
        var obj = Object.create(InnerObject).init(item);
        objects.push(obj);
      });
      return this;
    },
    update: function(idx) {
      var testObj = objects[idx];
      for (var prop in testObj) {
        testObj[prop] = '1';
      }
      return obj;
    },
    list: function() {
      return objects.slice();
    }
  }
})();

var item = {
  prop1: 'newFirst',
  prop2: 'newSecond',
  prop3: 'newThird'
}

var data = [item];

var obj = Object.create(Test).init(data);

console.log(obj.list()); // why the property value of each element here is 1
                         //when we are invoking update method below

                         //without update method it would log values       
                         // newFirst and so on...
obj.update(0);

答案 1 :(得分:0)

以下是两种可能的解决方案,它们构建类似于您所描述的数据:

data = [i.strip('\n').split('\t') for i in open('filename.txt')]
new_data = [dict(zip(data[0], i)) for i in data[1:]]

输出:

[{'Key3': 'Val3-A', 'Key2': 'Val2-A', 'Key1': 'Val1-A'}, {'Key3': 'Val3-B', 'Key2': 'Val2-B', 'Key1': 'Val1-B'}]

或者:

new_data = {a:list(b) for a, b in zip(data[0], zip(*data[1:]))}

输出:

{'Key3': ['Val3-A', 'Val3-B'], 'Key2': ['Val2-A', 'Val2-B'], 'Key1': ['Val1-A', 'Val1-B']}