gpt4 book ai didi

python - 比较嵌套字典和列表中的值

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:06 27 4
gpt4 key购买 nike

我想比较两个变量(字典和列表)的值。字典有一个嵌套结构,所以我必须循环所有项目。我发现了简单的解决方案,但我很确定我可以用更好的方式(使用 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 新手(我假设您能够通过观看上面的代码看到这一点)。

最佳答案

只需使用 error-safe dictionary lookup :

def _check(element, d, pattern = 'COL2'):
for user in d.itervalues():
if user.get(pattern) == element:
return True
return False

或者作为单行:

def _check(element, d, pattern = 'COL2'):
return any(user.get(pattern) == element for user in d.itervalues())

或者尝试将整个工作作为一句台词来完成:

#Finding which users should be removed from the database  
to_remove = set(
name
for name in users_from_database.itervalues()
if not any(user.get('COL2') == name for (user,) in users_from_client)
)

assert to_remove == {"val5", "val7"}

set可以使其更加简洁(高效):

to_remove = set(
user for (user,) in users_from_database
) - set(
user.get('COL2') for user in users_from_client
)
<小时/>

你的数据结构有点奇怪。考虑使用:

users_from_client = [
{
"COL1": "whatever",
"COL2": "val1",
"COL3": "whatever",
}, {
"COL1": "whatever",
"COL2": "val2",
"COL3": "whatever",
}, {
"COL1": "whatever",
"COL2": "val3",
"COL3": "whatever",
}
]

#variable containing users from the database
users_from_database = set(
"val1",
"val2",
"val5",
"val7"
)

这会将您的代码减少为:

to_remove = users_from_database - set(
user.get('COL2') for user in users_from_client
)

关于python - 比较嵌套字典和列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243899/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com