这是我的问题:
我正在用 Python 进行 LDAP 搜索。搜索将返回一个字典对象:
{'mail':['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95e0e6f0e7d5f8f4fcf9bbf6faf8" rel="noreferrer noopener nofollow">[email protected]</a>'],'mobile':['07852242242'], 'telephoneNumber':['01112512152']}
如您所见,返回的字典包含列表值。
有时会找不到结果:
{'mail':None, 'mobile':None, 'telephoneNumber':['01112512152']}
为了提取所需的值,我使用 get() 以避免字典项不存在时出现异常。
return {"uname":x.get('mail')[0], "telephone":x.get('telephoneNumber')[0], "mobile":x.get('mobile')[0]}
我想像上面一样返回我自己的字典,只包含字符串值,但我正在努力寻找一种有效的方法来检查列表是否为 None 并不断遇到索引错误或类型错误:
(<type 'exceptions.TypeError'>, TypeError("'NoneType' object is unsubscriptable",)
有没有办法在列表上使用 get() 方法,这样如果列表是 None 就不会抛出异常???
{"uname":x.get('mail').get(0)}
在不使用以下内容的情况下获取列表的第一个值或返回 None 的最有效方法是什么:
if isinstance(x.get('mail'),list):
或
if x.get('mail') is not None:
最佳答案
如果你想扁平化你的字典,你可以这样做:
>>> d = {'mail':None, 'mobile':None, 'telephoneNumber':['01112512152']}
>>>
>>> dict((k,v and v[0] or v) for k,v in d.items())
{'mail': None, 'mobile': None, 'telephoneNumber': '01112512152'}
如果您还想进行过滤,删除 None
值,那么您可以这样做:
>>> dict((k,v[0]) for k,v in d.items() if v)
{'telephoneNumber': '01112512152'}
关于python - 如果列表不是 None,则获取列表的第一个元素 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9327158/