我想比较两个变量(字典和列表)的值。字典有一个嵌套结构,所以我必须遍历所有项目。我发现了简单的解决方案,但我很确定我可以以更好的方式做到这一点(使用 python)。简而言之,我想查找变量user_from_database
中不存在的项目。user_from_client
我的解决方案:
#variable containing users from client side
users_from_client = {
"0": {
"COL1": "whatever",
"COL2": "val1",
"COL3": "whatever",
},
"1": {
"COL1": "whatever",
"COL2": "val2",
"COL3": "whatever",
},
"3": {
"COL1": "whatever",
"COL2": "val3",
"COL3": "whatever",
}
}
#variable containing users from the database
users_from_database = [
["val1"],
["val2"],
["val5"],
["val7"]
]
#This function is used to find element from the nested dictionaries(d)
def _check(element, d, pattern = 'COL2'):
exist = False
for k, user in d.iteritems():
for key, item in user.iteritems():
if key == pattern and item == element:
exist = True
return exist
#Finding which users should be removed from the database
to_remove = []
for user in users_from_db:
if not _check(user[0], users_from_agent):
if user[0] not in to_remove:
to_remove.append(user[0])
#to_remove list contains: [val5, val7"]
使用 python 方法给出相同结果的更好方法是什么?可能我不必补充说我是 python 的新手(我假设你可以看到上面的代码)。