如果list不是None,则获取list的第一个元素:Python [英] Get first element of list if list is not None: Python

查看:697
本文介绍了如果list不是None,则获取list的第一个元素:Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:

我正在Python中进行LDAP搜索.搜索将返回一个字典对象:

I am doing an LDAP search in Python. The search will return a dictionary object:

{'mail':['user@mail.com'],'mobile':['07852242242'], 'telephoneNumber':['01112512152']}

如您所见,返回的字典包含列表值.

As you can see, the returned dictionary contains list values.

有时候,找不到结果:

{'mail':None, 'mobile':None, 'telephoneNumber':['01112512152']}

要提取所需的值,我使用get()来避免字典项不存在时的异常.

To extract the required values, I am using get() as to avoid exceptions if the dictionary item does not exist.

return {"uname":x.get('mail')[0], "telephone":x.get('telephoneNumber')[0], "mobile":x.get('mobile')[0]}

我想返回上面的我自己的字典,只包含字符串值,但是我努力寻找一种有效的方法来检查列表是否为None并不断遇到索引错误或键入错误:

I want to return my own dictionary as above, with just the string values, but Im struggling to find an efficient way to check that the lists are not None and keep running into index errors or type errors:

(<type 'exceptions.TypeError'>, TypeError("'NoneType' object is unsubscriptable",)

有没有一种方法可以在列表上使用get()方法,因此,如果列表为None,则不会抛出异常?

Is there a way to use a get() method on a list, so that if the list is None it wont throw an exception???

{"uname":x.get('mail').get(0)}

不使用以下方法获取列表的第一个值或不返回任何值的最有效方法是什么:

What is the most efficient way of getting the first value of a list or returning None without using:

if isinstance(x.get('mail'),list):

if x.get('mail') is not None:

推荐答案

如果要拼合字典,可以执行以下操作:

If you want to flatten your dictionary, you can just do:

>>> 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值,则可以执行以下操作:

If you'd also like to filter, cutting off the None values, then you could do:

>>> dict((k,v[0]) for k,v in d.items() if v)
{'telephoneNumber': '01112512152'}

这篇关于如果list不是None,则获取list的第一个元素:Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆