检查字典是否包含true或false的数据,然后发送响应b

2024-09-28 17:24:02 发布

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

这是一个json响应,我从我的web客户端视图得到,我想检查这个列表字典是否包含数据或不是。怎么会我能继续吗?谢谢

 [
{
    "id": 41,
    "commercialOffice": false,
    "haveStoreRooms": false,
    "workFromHome": false,
    "seperateOffice": false,
    "receptionArea": false,
    "standardInsurance": false,
    "teamAudit": false,
    "auditReport": false,
    "receptionist": false,
    "qualityAssuranceTeam": false,
    "subContractor": null,
    "employeeIdentityCard": false,
    "employeeUniform": false,
    "insuranceList": "",
    "company": null
},
{
    "id": 45,
    "commercialOffice": false,
    "haveStoreRooms": false,
    "workFromHome": false,
    "seperateOffice": false,
    "receptionArea": false,
    "standardInsurance": false,
    "teamAudit": false,
    "auditReport": false,
    "receptionist": false,
    "qualityAssuranceTeam": false,
    "subContractor": null,
    "employeeIdentityCard": false,
    "employeeUniform": false,
    "insuranceList": "0",
    "company": 71
},
{
    "id": 46,
    "commercialOffice": true,
    "haveStoreRooms": true,
    "workFromHome": false,
    "seperateOffice": false,
    "receptionArea": false,
    "standardInsurance": true,
    "teamAudit": false,
    "auditReport": false,
    "receptionist": false,
    "qualityAssuranceTeam": false,
    "subContractor": null,
    "employeeIdentityCard": true,
    "employeeUniform": false,
    "insuranceList": "0",
    "company": 68
},

]

我在想这个

def (self):
   dic = {'key1': ['value1', 'value2'],
       'key2':  'value77' }
       values = dic.values()
      'value77' in [x for v in values for x in v if type(v)==list] or 
      'value77' in values

Tags: inidfalsetruenullvaluesreceptionistworkfromhome
2条回答

这取决于你所说的数据是什么意思。有录音机钥匙吗?它是给定的dict密钥吗?你知道吗

在Python中,空dict是错误的,因此只要调用列表中的^{}就会告诉您每个dict是否至少有一个键值对:

>>> all( [ {1:2}, {'A':'B'} ] )
True
>>> all( [ {1:2}, {'A':'B'}, {}, {3:4}] )
False

如果要检查每个dict中是否存在给定的键,可以将列表理解与get结合起来。你知道吗

使用in运算符:

if b in a:

演示:

>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False

由@Eric Duminil解释的那个是更好的答案

根据您的要求更新:

dic_3 = {'key1': ['value1', 'value2'],'key2':  '','key3':None }
for key, value in dic_3.iteritems():
    if value is None or value =='':
        print key ,"is Empty"

输出:

key3 is Empty
key2 is Empty

相关问题 更多 >