Search code examples
pythondictionarygenerator-expression

Load options dictionary using generator expression


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 ??


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)}