如何返回字典列表和基于特定对象的对象列表之间的差异关键字:仅值

2024-05-15 10:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据现有条目和用户传递的内容之间的差异来更新表中的条目。你知道吗

例如:

通过的内容:

users: [
    {"id": 1, "email": "email1@gmail.com"}, 
    {"id": 2, "email": "email2@gmail.com"}
]

以及已经存在的:

user_playground = UserPlaygroundModel.query.filter_by(playground=playground).all()

# This will be a list of UserPlayground objects
user_playground = [
    {id=1, playground=sandbox},
    {id=3, playground=sandbox}
]

所以这意味着1留在表中,2将被添加,3将被删除。你知道吗

我想输出传递的内容和已经存在的内容之间的差异,然后基于此更改条目。你知道吗

users_to_add = {id=2, "email": "email2@gmail.com"}

users_to_delete = {id=3}

有没有更好的办法?你知道吗


Tags: to用户comid内容email条目差异
2条回答

如果我理解正确,我认为这就是你需要的:

users = [
    {"id": 1, "email": "email1@gmail.com"},
    {"id": 2, "email": "email2@gmail.com"}
]

user_play =[
    {"id":1, "playground": "sandbox"},
    {"id":3, "playground": "sandbox"}
]


users_to_add = [u for u in users if u.get('id') not in [x.get('id') for x in user_play]]

users_to_delete = [u for u in user_play if u.get('id') not in [x.get('id') for x in users]]

print(users_to_add) # output : [{'id': 2, 'email': 'email2@gmail.com'}]

print(users_to_delete) # output : [{'id': 3, 'playground': 'sandbox'}]

你需要添加的用户是“我从我的文章中得到的所有不在数据库中的用户”。类似地,您要删除的用户是“我数据库中的所有用户,但我在帖子中没有得到这些用户”。你知道吗

在python中,可以使用以下两行代码实现这一点:

# All users supplied from post body (i guess?) that is not in the db
users_to_add = [u for u in users_from_post if u.id not in [x.id for x in user_playground]]

# All users from db that was not supplied by the post (i think?)
users_to_delete = [u for u in user_playground if u.id not in [x.id for x in users_from_post]]

如果你有很多用户,可以做一些事情来优化这个,但是这个想法是正确的。你知道吗

相关问题 更多 >