简体   繁体   English

如果list不是None,则获取list的第一个元素:Python

[英]Get first element of list if list is not None: Python

Here is my issue: 这是我的问题:

I am doing an LDAP search in Python. 我正在Python中进行LDAP搜索。 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. 如您所见,返回的字典包含列表值。

Sometimes, no result will be found: 有时,找不到结果:

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

To extract the required values, I am using get() as to avoid exceptions if the dictionary item does not exist. 为了提取所需的值,我使用get()来避免字典项不存在时的异常。

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

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

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

Is there a way to use a get() method on a list, so that if the list is None it wont throw an exception??? 有没有一种方法可以在列表上使用get()方法,因此,如果列表为None,则不会抛出异常?

{"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):

or 要么

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'}

If you'd also like to filter, cutting off the None values, then you could do: 如果您还想过滤,切掉None值,则可以执行以下操作:

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

Try the next: 尝试下一个:

return {"uname":(x.get('mail') or [None])[0], ...

It is a bit unreadable, so you probably want to wrap it into some helper function. 它有点不可读,因此您可能希望将其包装到一些辅助函数中。

You could do something like this: 您可以执行以下操作:

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

input_key_map = {
    'mail': 'uname',
    'telephoneNumber': 'telephone',
    'mobile': 'mobile',
}

dict((new_name, input_dict[old_name][0]) 
      for old_name, new_name in input_key_map.items() if input_dict.get(old_name))

# would print:
{'telephone': '01112512152'}

I'm not sure if there's a straightforward way to do this, but you can try: 我不确定是否有直接的方法可以执行此操作,但是您可以尝试:

 default_value = [None]
 new_x = dict((k, default_value if not v  else v) for k, v in x.iteritems())

And use new_x instead of x . 并使用new_x而不是x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM