python--import data from file and autopopulate a dictionary

Viewed 516

I am a python newbie and am trying to accomplish the following. A text file contains data in a slightly weird format and I was wondering whether there is an easy way to parse it and auto-fill an empty dictionary with the correct keys and values.

The data looks something like this

01> A B 2          ##01> denotes the line number, that's all
02> EWMWEM         
03> C D 3
04> EWWMWWST
05> Q R 4
06> WESTMMMWW

So each pair of lines describe a full set of instructions for a robot arm. For lines 1-2 is for arm1, 3-4 is for arm 2, and so on. The first line states the location and the second line states the set of instructions (movement, changes in direction, turns, etc.)

What I am looking for is a way to import this text file, parse it properly, and populate a dictionary that will generate automatic keys. Note the file only contains value. This is why I am having a hard time. How do I tell the program to generate armX (where X is the ID from 1 to n) and assign a tuple (or a pair) to it such that the dictionary reads.

dict = {'arm1': ('A''B'2, EWMWEM) ...}

I am sorry if the newbie-ish vocab is redundant or unclear. Please let me know and I will be happy to clarify.

A commented code that is easy to understand will help me learn the concepts and motivation.

Just to provide some context. The point of the program is to load all the instructions and then execute the methods on the arms. So if you think there is a more elegant way to do it without loading all the instructions, please suggest.

3 Answers

I would do something like that:

mydict = {} # empty dict
buffer = ''
for line in open('myFile'): # open the file, read line by line
    linelist = line.strip().replace(' ', '').split('>') # line 1 would become ['01', 'AB2']
    if len(linelist) > 1: # eliminates empty lines
        number = int(linelist[0])
        if number % 2: # location line
            buffer = linelist[1] # we keep this till we know the instruction
        else:
            mydict['arm%i' % number/2] = (buffer, linelist[1]) # we know the instructions, we write all to the dict
def get_instructions_dict(instructions_file):
    even_lines = []
    odd_lines = []
    with open(instructions_file) as f:
        i = 1
        for line in f:
            # split the lines into id and command lines
            if i % 2==0:
                # command line
                even_lines.append(line.strip())
            else:
                # id line
                odd_lines.append(line.strip())
            i += 1

    # create tuples of (id, cmd) and zip them with armX ( armX, (id, command) )
    # and combine them into a dict
    result = dict( zip ( tuple("arm%s" % i for i in range(1,len(odd_lines)+1)),
                      tuple(zip(odd_lines,even_lines)) ) )

    return result

>>> print get_instructions_dict('instructions.txt')
{'arm3': ('Q R 4', 'WESTMMMWW'), 'arm1': ('A B 2', 'EWMWEM'), 'arm2': ('C D 3', 'EWWMWWST')}

Note dict keys are not ordered. If that matters, use OrderedDict

robot_dict = {}
arm_number = 1
key = None
for line in open('sample.txt'):
   line = line.strip().replace("\n",'')
   if not key:
       location = line
       key = 'arm' + str(arm_number) #setting key for dict
   else:
       instruction = line
       robot_dict[key] = (location,line)
       key = None #reset key
       arm_number = arm_number + 1
Related