Is there an easy one liner to convert a text file to a dictionary in Python without using CSV?

时间:2016-02-12 21:35:32

标签: python file dictionary text

I have a 10,000 line file called "number_file" like this with four columns of numbers.

lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)

I need to convert the file to a dictionary where the first column numbers are the keys and the entire line are the values

So far, I tried this but it didn't work.

12123 12312321 12312312 12312312
12123 12312321 12312312 12312312
12123 12312321 12312312 12312312
12123 12312321 12312312 12312312

How do I fix this one liner so that it converts the file to a dictionary?

2 个答案:

答案 0 :(得分:7)

You could use the following dict comprehension:

import UIKit

@IBDesignable extension UIView {
    @IBInspectable var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            guard let color = layer.borderColor else {
                return nil
            }
            return UIColor(cgColor: color)
        }
    }
    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

where the with open(number_file) as fileobj: result = {row[0]: row[1:] for line in fileobj for row in (line.split(),)} is effectively an assignment.

Or you could use a nested generator expression to handle the splitting of each line:

for row in (one_element_tuple,)

However, if your file is really tab-delimited, don't fear the with open(number_file) as fileobj: result = {row[0]: row[1:] for row in (line.split() for line in fileobj)} module:

csv

答案 1 :(得分:1)

split()使用 maxsplit 参数来限制分割字符串的次数。

with open(file_name) as f:
    data = dict(line.strip().split(maxsplit=1) for line in f)