Search code examples
pythondictionary-comprehensionfor-comprehension

Python dictionary comprehension from file


I am trying to make everything in my python code with comprehension. I had to convert a .txt file data to dict. It looked like this:

A   .-
B   -...
C   -.-.
...

Yeah, it's morse code.

My code looks like this:

def morse_file_to_dict(filename):
    d = {}
    for line in open(filename):
        ch, sign = line.strip().split('\t')
        d[ch] = sign
    return d

It gives back a normal dict like this:

{'A': '.-', 'B': '-...', 'C': '-.-.', ... }

My question is, can i make this in one line? With comprehension?

Thank you for your time and answer!


Solution

  • Your function can become:

    def morse_file_to_dict(filename):
        with open(filename) as fh:    
            return dict(l.strip().split() for l in fh)
    

    This takes advantage of creating a dict from tuples.

    If there is a chance that there are more than two fields, you should use:

    def morse_file_to_dict(filename):
        with open(filename) as fh:    
            return dict(l.strip().split("\t", 1) for l in fh)
    

    This second example specifically sets the sep and maxsplit parameters of str.split