7

So I need to create a list which will save the users inputs (a name and their 3 scores) and that will then append this information to one of 3 files. I tried doing this by appending the data to a list and then the list to a dictionary but this doesn't seem to work. I am really new to python so would really appreciate any help. This is my code so far:

dict1 = {}
dict2 = {}
dict3 = {}
list1 = []
list2 =[]
list3 =[]

def main():
    name= input ('What is your name?')
    for i in range(0,3)
        score = input("Enter your score: ")
        clss =input('which class?')
        if clss==1:
            list1.append (name, score)
        elif clss==2:
            list2.append (name, score)
        elif clss==3:
            list3.append (name, score)

Here I want to append the list to one of 3 dictionaries depending on the class:

def loop():
    x=input('Do you want to make an entry?')
    if x=='Yes':
        main()
    elif x=='No':
        sys.exit(0)  

loop()
Kins
  • 547
  • 1
  • 5
  • 22
Rutwb2
  • 147
  • 2
  • 2
  • 7

3 Answers3

7

You need to have lists in dictionary to be able to append to them. You can do something like:

scores = {"class1": [], "class2": [], "class3": []} 

def main():
    name= input ('What is your name?')
    for i in range(0,3)
        score = input("Enter your score: ")
        clss =input('which class?')
        if clss==1:
            scores["class1"].append({"name": name, "score": score}) 
        elif clss==2:
            scores["class2"].append({"name": name, "score": score}) 
        elif clss==3:
            scores["class3"].append({"name": name, "score": score}) 
    print scores
Teemu Kurppa
  • 4,779
  • 2
  • 32
  • 38
2

Have you tried to use defaultdict ? Example from the python docs:

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

You can see another example of using defaultdict here

Community
  • 1
  • 1
Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31
1
dictionary = {i:x for i,x in enumerate([['List', 'one'],['List', 'two']])}

A somewhat different approach would be this, I'm unsure if this is what you mean but I tried my best understanding. I also tried keeping it as simple as possible.

d = {}

while True:
    # Ask the user to make a new entry.
    raw = raw_input('Make a new entry?')

    if raw.lower() in ['y', 'yes']: 
        # Ask the users name.
        name = raw_input('Your name?')

        # Create new entrypoint in the dictionary containing a empty list bound to the name
        d[name] = []

        for score in range(3):
            # Ask the user for three scores
            d[name].append(raw_input('Enter a new score: '))

   # If the input doesn't match you break out of the loop.
    else:
        break

    # You can at any time print the contents of the dictionary.
    # print d
Katpoes
  • 209
  • 1
  • 11