简体   繁体   English

如何向Python中的字典列表中已有的KEY添加数据 3

[英]How to add data to an already existing KEY in a List of Dictionary in Python 3

So I have a list of dictionaries below所以我在下面有一个字典列表

users = [
          {
            "username" : "Sarthak",
            "password" : "Sartagarwal1",
            "faves" : ["Shake It Off", "Clocks"]
          },
          {
            "username" : "Sharma21",
            "password" : "Shame200521",
            "faves" : ["Roar", "Shake It Off", "Believer"]
          }
        ]

And what I want to do is let the user create an account.而我想要做的是让用户创建一个帐户。 So I ask them for a Username and a Password.所以我要求他们提供用户名和密码。 After that, I want to create a new dictionary for that new user.之后,我想为那个新用户创建一个新词典。 But I don't know how to add that.但我不知道如何添加。

I have tried using the update() method and also searched online.我试过使用 update() 方法,也在网上搜索过。 But I just can't figure it out, I do have a JSON file where all this data is saved and I saw the dump() function but I don't really know if I am supposed to use that in my certain situation.但我就是想不通,我确实有一个 JSON 文件,其中保存了所有这些数据,我看到了 dump() function 但我真的不知道我是否应该在我的特定情况下使用它。

I would really appreciate it if someone can help me out:)如果有人能帮助我,我将不胜感激:)

Thank you in advance and Have a great day!提前谢谢你,祝你有美好的一天!

users is a list instead of dictionary here. users 在这里是一个列表而不是字典。 You can use the append method:您可以使用 append 方法:

users.append(
    {
        "username" : "user1",
        "password" : "pass1",
        "faves" : ["Shake It Off", "Clocks"]
    }
)

print(users)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM