Python return dictionary [closed]

2024/11/17 7:42:34

I am trying to create a dictionary of user input. This dictionary takes any user input (ex. "I like pie") and will list each value with its respective index. However, my buildIndex function will not return a the dictionary created within the function. Can anyone give some insight as to why this might be happening?

d = {}
def buildIndex(m):m = m.lower() words = m.split()i = 0while i < len(words):nextWord = words[i]if nextWord in d:ref = [d[nextWord]]ref.append(i)d[nextWord] = refelse:d[nextWord] = ii += 1return d
Answer

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.

https://en.xdnf.cn/q/120232.html

Related Q&A

Use selenium and python to move mouse outside of web page area

I need to test the exit intent form on this page: https://www.graphicproducts.com/guides/5s-system/When the mouse pointer is moved outside of the web page area a popup window appears. I then need to en…

Python „stack overflow” (104 if statements). Is def(x) the only solution to optimise code?

Today have tried to check files with path directory name. Previously it worked, until I tried to create 104 if/else statements. How to dispose of this overflow error? More specific question: Does def(…

How to fix Python restarting whenever I start program on IDLE environment?

import randomwinning_conditon = 0 no_of_guesses = 0 comp_guess = random.randint(1,100)while (no_of_guesses == 11) or (winning_conditon == 1):user_guess = int(input("What is your guess? "))if…

Fetching Lawyers details from a set of urls using bs4 in python

I am an absolute beginner to Web Scraping using Python and know very little about programming in Python. I am just trying to extract the information of the lawyers in the Tennessee location. In the web…

Having trouble with python simple code running in console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

.upper not working in python

I currently have this codenum_lines = int(input()) lines = [] tempy = ctr = 1 abc = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z } for i in range(0, num_lines):tempy = input()lines.append([])l…

Python SKlearn fit method not working

Im working on a project using Python(3.6) and Sklearn.I have done classifications but when I try to apply it for reshaping in order to use it with fit method of sklearn it returns an error. Heres what …

extracting n grams from huge text

For example we have following text:"Spark is a framework for writing fast, distributed programs. Sparksolves similar problems as Hadoop MapReduce does but with a fastin-memory approach and a clean…

Python: Input validate with string length

Ok so i need to ensure that a phone number length is correct. I came up with this but get a syntax error.phone = int(input("Please enter the customers Phone Number.")) if len(str(phone)) == 1…

Mergesort Python implementation

I have seen a lot of mergesort Python implementation and I came up with the following code. The general logic is working fine, but it is not returning the right results. How can I fix it? Code: def me…