您可以将列表附加到字典吗?

Can you append a list to a dictionary?

所以我需要创建一个列表来保存用户输入(姓名和他们的 3 个分数),然后将此信息附加到 3 个文件之一。我尝试通过将数据附加到列表然后将列表附加到字典来执行此操作,但这似乎不起作用。我是 python 的新手,非常感谢您的帮助。 到目前为止,这是我的代码;

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)

这里我想根据 class

将列表附加到 3 个词典之一
def loop():
    x=input('Do you want to make an entry?')
    if x=='Yes':
        main()
    elif x=='No':
        sys.exit(0)  

loop()

您尝试过使用 defaultdict 吗? python 文档中的示例:

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

你可以看到另一个使用defaultdict的例子here

您需要在字典中有列表才能附加到它们。你可以这样做:

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
dictionary = {i:x for i,x in enumerate([['List', 'one'],['List', 'two']])}

这是一种稍微不同的方法,我不确定这是否是您的意思,但我已尽力理解。我也尽量保持简单。

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