Question

I have option file in this format:

key value\t\n

N:B:. Some values show tab after it.

I use Code like :

        src               = open("conf.cfg").readlines()
        item          =  item.split(" ")[0:2]
        key           =   item[0]
        value         =   item[1]
        dict_[key]    = value

Can I use generator expression to get the same result ??

Was it helpful?

Solution

You could use a dictionary comprehension, for example:

with open("conf.cfg") as f:
    dict_ = {key: value 
             for key, value in (line.strip().split(" ")[:2] 
                                for line in f)}

OTHER TIPS

Maybe this way:

with open('config.txt') as f:
    dict_ = {k: v for k, v in (line.split() for line in f.readlines())}

Yes, you can use a generator expression, it would look like this:

with open("conf.cfg") as f:
    dict_ = dict(line.split() for line in f)    

I am assuming you don't have spaces in the keys or values. If you have spaces in them (and "they are quoted" strings) then it will be easier for you to read your file with the csv module.

Using generator function:

def myGenerator():
    with open("conf.cfg") as f:
        for line in f.readlines():
            yield(line.split())

result = {k:v for k,v in myGenerator()}

print result
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top