0

My code is:

quiz = {}
quiz["questions"]={}
templist = []

def checkint(i):
    try:
        int(i)
        return True
    except ValueError:
        return False


with open("sample",'r') as f:
    for x in f:
        x.rstrip()
        num,text = x.split(" ",1)
        print(text)
        num = num[:-1]
        if checkint(num):
            quiz["questions"][num] = {}
            quiz["questions"][num]["question"] = text
            templist.append(num)
        else:
            qn = templist.pop()
            quiz["questions"][qn][num] = text   
            templist.append(qn)

The sample file is:

1. Who is the sower in the parable of wheat and tares?

 a. Jesus

 b. Peter

 c. Angels

 d. Satan

When I print the dictionary quiz, the output contains newline \n at the end of every value.

{'questions': {'1': {'a': 'Jesus\n', 'b': 'Peter\n', 'c': 'Angels\n', 'd': 'Satan\n', 'question': 'Who is the sower in the parable of wheat and tares?\n'}, '2': {'question': '\n'}}}

Why is this so? What should I do to get rid of the \n?

Taku
  • 31,927
  • 11
  • 74
  • 85
One Face
  • 417
  • 4
  • 10
  • This has nothing to do with dictionaries -- your lines read from the file would still have trailing newlines if you never wrote them to a dictionary at all. Please in the future try to produce a [mcve] with elements not strictly necessary to recreate the problem removed. – Charles Duffy May 21 '17 at 16:04
  • `x = x.strip()` – khelwood May 21 '17 at 16:04

1 Answers1

3

rstrip return a copy of the string with trailing characters removed.

Change this:

x.rstrip()

To:

x = x.rstrip()

EDIT:

The second argument you give in num,text = x.split(" ",1) means that :

if maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If there is nothing to split you will get this error.

Have you tried num,text = x.split(" ")?

Or at least one split is a mandatory?

omri_saadon
  • 10,193
  • 7
  • 33
  • 58