Reputation: 35
How can I store multiples values in a dictionary?
Upvotes: 3
Views: 2227
Reputation: 2569
A dictionary that stores records of students, even if they have the same name:
stud_data = {}
while True:
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the grade :")
repeat = input("Do you want to add input more?: ")
if not Name in stud_data:
stud_data[Name] = []
stud_data[Name].append({
"Name": Name,
"Age": Age,
"Gender": Gender
})
if repeat == "no" or repeat == "NO":
break
Querying the dict:
name = input("Enter student name: ")
print(stud_data.get(name, "Record is not in the dictionary"))
Upvotes: 2
Reputation: 83
Kim mentioned they are supposed to do lookups of students in the final step. One could search the list but I believe a dict is the better choice. I'd suggest:
stud_data = {}
while True:
name = input("Enter the student name :")
age = input("Enter the age :")
gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data[name] = {'age': age, 'gender': gender}
if repeat.lower() == "no":
break
searched_name = input("Enter name to lookup :")
print(searched_name,stud_data.get(searched_name,"Record is not in the dictionary"))
Of course Kim will want to clean up the final print.
Upvotes: 4
Reputation: 59
As it's said above, you could use a dictionary of lists. But instead of the break statement I would use the same "repeat" variable.
`stud_data = {"Name": [],
"Age": [],
"Gender": []}
repeat = 'yes'
while repeat == "yes" or repeat == "YES":
print(repr(repeat))
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data['Name'].append(Name)
stud_data['Age'].append(Age)
stud_data['Gender'].append(Gender)
print(stud_data)`
Upvotes: 2
Reputation: 81684
Looks like you expect stud_data
to be a list of dictionaries and not a dictionary, so make it a list and use .append
instead of .update
.
Also:
You will need to shift things around if you actually indent to allow the user input multiple times.
You don't need flag
. Use while True
and break
when needed
No need for parentheses around a single value
stud_data = []
while True:
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data.append({
"Name": Name,
"Age": Age,
"Gender": Gender
})
if repeat == "no" or repeat == "NO":
break
print(stud_data)
Upvotes: 3