使用Python检查项目是否在字典中并且为true

2024-04-18 23:56:11 发布

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

我收到一个JSON字典,我想检查某些键是否存在并且是真的。你知道吗

我用all(i in incoming_json for i in ['title', 'code', 'university', 'lecturer'])检查它们是否存在,但我一直在检查它们是否是真的。你知道吗

我试过all(i in incoming_json and True for i in ['title', 'code', 'university', 'lecturer'])all(i in incoming_json for i in ['title', 'code', 'university', 'lecturer'] if i),但它们似乎没有任何区别。你知道吗

我做错什么了?你知道吗

JSON示例:

{title: "Example title", code: "1234", university: "2", lecturer: "John Doe"}

澄清:我只需要知道他们是真是假。你知道吗

编辑:谢谢你的回复,我本可以接受其中任何一个,但我接受了一个解释我做错了什么。你知道吗


Tags: andinjsontrueforif字典title
3条回答

and True检查一下。。嗯,没什么,因为TrueTruei in incoming_json and incoming_json[i]将检查在incoming_json中表示的键的值是否也是真的(或者评估为True的值)。你知道吗

如果确实要检查布尔值True(而不是1等),请使用incoming_json[i] is True。你知道吗

只需使用incoming_json.get(i)即可返回键的值,如果键不存在,则使用None,如下所示:

all(incoming_json.get(i) for i in ['title', 'code', 'university', 'lecturer'])

只有在字典中不存在值或者值为False时,才会返回False

您可以这样尝试:

all(incoming_json[i] if i in incoming_json else False for i in ['title', 'code', 'university', 'lecturer'])

相关问题 更多 >