[Solved] Python return dictionary [closed]


You seem to be approaching this as if it is C. That is understandable, but overcomplicating your Python. Let’s consider just a few things.

Overwriting an input variable immediately:

def buildIndex(m, d):
    d = {}

In Python we don’t need to declare variables or make room for them. So this is much more clearly expressed as:

def build_index(m):
    d = {}

(You notice I changed from functionName camelCase to underscore_naming — that is pretty common. CamelCase is more common for class names in Python.)

Using an explicit iterator variable:

Python has a concept of iterables. This means any list-of-things type object can be assigned on the fly:

while i < len(words):
    nextWord = words[i]

becomes:

for word in words:
    if word in d:
        # etc...

or even:

for word in m.split():
    # blahblah

Overwriting things in the middle of your procedure:

Consider carefully what this section is doing. Step through it in your head.

if nextWord in d:
    ref = [d[nextWord]]
    ref.append(i)
    d[nextWord] = ref
else:
    d[nextWord] = i

What is the purpose of your dictionary? Build a word count? Keep a dictionary of locations-within-the-input-string? …?!? As it is, this doesn’t appear to do anything particularly useful. Even if it did, why it is OK to have a list value in some places and a non-list integer value in others? Pick a type and stick to it — that will make things much easier.

You asked for insight, not for anyone to do your homework for you — very cool. Consider the points above carefully, and read the docs on dictionaries (there are functions in there that will help you a lot — particularly the dict() constructor…).

You’re not too far off — just need to get some Python idioms down.

solved Python return dictionary [closed]