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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28782883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:45:27  来源:igfitidea点击:

Can you append a list to a dictionary?

pythonlistdictionary

提问by Rutwb2

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;

所以我需要创建一个列表来保存用户输入(一个名字和他们的 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)

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

在这里,我想根据课程将列表附加到 3 个词典之一

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

loop()

采纳答案by Teemu Kurppa

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

回答by Aleksander Monk

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

您是否尝试过使用 defaultdict ?来自 python 文档的示例:

>>> 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

您可以在此处查看使用 defaultdict 的另一个示例

回答by Katpoes

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