Code error control flow , dictionary


#1

What is wrong with the code here? I am getting the error as: ValueError: dictionary update sequence element #0 has length 1; 2 is required

my code -

data = []
n = int(input("Enter the no. of students whose data is to be input:\n"))
c = 0
while c < n:
    name = input("Enter name\n name = ").split('=')
    data.append(name)
    age = input("Enter age\n age = ").split('=')
    data.append(age)
    Class = input("Enter class\a class = ").split('=')
    data.append(Class)
    ph_no = input("Enter phone number\n ph_no = ").split('=')
    data.append(ph_no)
    c = c + 1

print(data)
info=dict(data)
print(info)

Please help asap.
thanks


#2

doing this:

name = input("Enter name\n name = ").split('=')

means the user is required to input: name=krtikapareek

if the user only enters krtikapareek, there is nothing to .split(), so the name variable is a single value, which can’t be converted to dictionary, given a dictionary needs key and value


#3

the (name = ) in print statement is given so that the user doesn’t need to write it again and again… Does the user still need to input: name=stetim94 for the dictionary to work? if yes, how to eradicate this ?


#4

no, "Enter name\n name = " is only a message displayed to the user (so the user knows what to do/to expect).

yes

that is a good question, i know the answer, but what do you think is possible?


#5

can formatting be applied?
As : print ( “name = { }”. format(name) )


#6

Why would you do that?

Wait, i walked over your code again:

entering two students and converting to dictionary will only preserve a single student, how do you even want to have this?


#7

Oh my!!!
Please explain why is this happening . What ways are there to do the task?


#8

well, the dict() function adds age key to dictionary (first student) then you add another age key, but keys have to be unique, so it will overwrite the age key of first student

the solution is very likely that you need a mixture of list(s) and dictionary(ies). It really depends on what the assignment is.

Here is the thing, i could solve it, but is that what you want? shouldn’t you solve it? Its your assignment. Solving it yourself will teach you far more, maybe back to the drawing board?


#9

Oh, right.
I’ll get back to you after a few more tries maybe.:sweat_smile:
Thank you so much for the support :smile:


#10

Let me know if you need further help. Don’t forget that we can add to a dictionary manually as well:

dict[key] = "new value"

playing around with this might help you better understand dict()


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.