Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you append a list to a dictionary?

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()
like image 230
Rutwb2 Avatar asked Feb 28 '15 14:02

Rutwb2


People also ask

Can we append list in dictionary?

Appending a dictionary to a list with the same key and different values. Using append() method. Using copy() method to list using append() method. Using deepcopy() method to list using append() method.

Can you append a list to a dictionary Python?

By using ” + ” operator we can append the lists of each key inside a dictionary in Python.

How do I add a list to a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.


2 Answers

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
like image 160
Teemu Kurppa Avatar answered Sep 21 '22 12:09

Teemu Kurppa


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

like image 28
Aleksander Monk Avatar answered Sep 20 '22 12:09

Aleksander Monk