2 Replies - 229 Views - Last Post: 03 December 2019 - 02:25 AM Rate Topic: -----

#1 fearless_swami   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 24-September 18

Parsing user input in python...

Posted 18 October 2019 - 12:49 PM

Hello,

I am writing a simple python program where the first line of the user input is a number, and that number is used to iterate through the next lines of what a user types, which are key-value pairs that will be added to a dictionary. So, if the first line of the user input is 3, then the next lines will be three dictionary entries, where the string of the input is split by a space, (i.e. "a 1", where a is the key and 1 is the value). The issue I am running into is that when I parse the string at index 0, and print out what is stored there is returns both the key and value, rather than just the key. So, if the user inputs "a 1" and I do print(string[0]), the value printed is "a 1" not just "a". I want to add to my dictionary using the index 0 as the key and index 1, as the value, and I have split by a space. Below is the code I have for my loop:

def main():

    dict = {}

    num = int(sys.stdin.readline())

    for i in range(num_of_cands):
        q_inp = sys.stdin.readline(1)
        entry = q_inp.split(" ")


        print(entry[0]))




This is output:

3
a 1
a

1




I am also not sure why the loop stops iterating, and why the dictionary entry has a new line between what is supposed to be the key and value respectively

Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Parsing user input in python...

#2 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 561
  • View blog
  • Posts: 1,794
  • Joined: 27-December 13

Re: Parsing user input in python...

Posted 18 October 2019 - 02:43 PM

In line 8 you do q_inp = sys.stdin.readline(1).
That "1" placed as argument for the readline function essentially makes the line read one character at a time.
And by coincidence, you iterate 3 times through a string of length 3: "a 1" thus you output becomes:
a

1
Three lines with one character on each.

In short: Just drop the "1" argument.
Was This Post Helpful? 1
  • +
  • -

#3 Histiogge   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 11
  • Joined: 03-December 19

Re: Parsing user input in python...

Posted 03 December 2019 - 02:25 AM

I'd simply eliminate the "1" argument :bigsmile:.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1