user7222454 user7222454 - 9 days ago 5
Python Question

Can someone explain how to store and display a line count with user input?

This simple while loop that stops at a sentinel value and otherwise continuously asks for user input.
How would I use the

incrementing
line count variable to display after on what line the user inputted certain things? I would guess use of a dictionary is needed?

lineCount = 1
d = {} #is this needed?
q = raw_input("enter something")
while q != "no":
lineCount += 1
q = raw_input("enter something")
#code here that stores each new input with its respective line and prints what the user inputted on each corresponding line when the loop ends


Many thanks in advance

Answer

Exactly like you said, using a dictionary:

d = {}
lineCount = 1
q = raw_input("enter something: ")
while q != "no":
    lineCount += 1
    q = raw_input("enter something: ")
    d[lineCount] = q

Then you could just query your dictionary if you want to know what the user input at a desired line as d[desired_line].

Assuming you have a simple dictionary, such as:

d = {2: 'b', 3: 'c', 4: 'd', 5: 'no', 6: 'c'}

Then if you'd like to print out the lines where a desired word appear you could define a function like so:

def print_lines(my_dict, word):
    lines = [line for line, ww in d.iteritems() if ww == word]
    return lines

You could call this function with your dictionary (d) and the word your looking for, let's say 'c':

print_lines(d, 'c')