Python - import data from a file and autopopulate a dictionary

I am new to python and trying to do the following. The text file contains the data in a slightly strange format, and I was wondering if there is an easy way to parse it and automatically fill the empty dictionary with the correct keys and values.

The data looks something like this:

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

So, each pair of lines describes a complete set of instructions for the robot arm. For lines 1-2 for arm 1, 3-4 for arm 2 and so on. The first line indicates the location, and the second line contains a set of instructions (moving, changing direction, turning, etc.).

I am looking for a way to import this text file, parse it correctly and populate a dictionary that will generate automatic keys. Note that the file contains only the value. That’s why it’s hard for me. How to tell the program to generate armX (where X is an identifier from 1 to n) and assign it a tuple (or pair) in such a way that the dictionary reads.

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

I apologize if the beginner-ish-vocals are redundant or unclear. Please let me know and I will be happy to clarify.

Easy-to-understand commented code will help me learn concepts and motivation.

Just to provide some context. The point of the program is to download all the instructions and then execute the methods on hand. Therefore, if you think there is a more elegant way to do this without downloading all the instructions, please suggest.

+4
3

- :

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

dict . , OrderedDict

0
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
-1
source

All Articles