Question: I've been trying to create a script that searches for a pattern in a text file, counts the number of times it occurs and then inserts this as a key-value pair into a dictionary.

Here's the code:

```
fname = raw_input("File name: ")
import re
vars = dict()
lst= list()
count = 0

try:
    fhand = open(fname, "r+")
except:
    print "File not found"
quit()  

for line in fhand:
    line.rstrip()
    if re.search(pattern , line):
        x = re.findall(pattern , line)
        lst.append(x)
    else:
        continue
    for x in lst:
        count += 1

```

What would be the best way to extract text from the regex method and insert it into a dictionary to make it look like this:

```
{'pattern' : count, 'pattern' : count, 'pattern' : count}

```

Answer: 
Numpy can do this as well, quite effeciently! Using the lookup table from Peter Wood's answer we can write for the x-direction:

```
x0 = 100
directions = np.cumsum(2 - dragon) % 4
dx = np.take([0, -1, 0, 1], directions)
x = np.cumsum(np.r_[x0, dx])

```

The `2 - dragon` is to get rid of negative values before taking the modulus.
Here is a way using a dictionary lookup, I think it's more suitable to use a `tuple` to indicate your position and a `list` to represent the entire path.

I don't have your results, so make sure the `face_dict` is set up properly.

```
dragon = [1, 1, -1, 1, 1, -1, -1]
# format: old-direction -> (add-to-x, add-to-y, new-direction)
# using a list would be faster, but I don't have time to think about it :)
face_dict = {
    "EAST": {-1: (1, 0, "NORTH"), 1: (1, 0, "SOUTH")},
    "SOUTH": {-1: (0, -1, "EAST"), 1: (0, -1, "WEST")},
    "WEST": {-1: (1, 0, "SOUTH"), 1: (1, 0, "NORTH")},
    "NORTH": {-1: (0, 1, "WEST"), 1: (0, 1, "EAST")}
}

# indicate a position using a tuple, a tuple represents a single location
# while a list is suitable to represent a path
pos = (100, 100)
def make_path(directions, start_pos):
    # create empty path with starting position
    path = [None] * len(dragon)
    path[0] = start_pos

    # this is the current state, which is stored in the list after every step.
    current_pos = start_pos
    # this is where we're facing right now
    face = "EAST"
    # each iteration fills a single step in the semi-empty path
    for index, direction in enumerate(directions):
        move = face_dict[face][direction]
        current_pos = (current_pos[0] + move[0], current_pos[1] + move[1])
        face = move[2]
        path[index] = current_pos
    return path

```

**note:** Combining [Peter Wood's solution](https://stackoverflow.com/a/27863868/948550) can optimize the lookup on each iteration.