Trying to write a function to search a requests response converted into a list of dictionaries. Each user returned will have many attributes, but I need to find users, by display_name
based on the query passed through the main function.
Currently getting an error:
if query in user['display_name']: TypeError: argument of type 'NoneType' is not iterable
Function Definition
def search_users(self, query, group='any'):
# Returns list of dictionaries representing users
users = self.get_all_users()
for user in users:
if query in user['display_name']:
result_set.append(user)
Main function call
looker.search_users('steve')
just change the line :
if query in user['display_name']:
to
if query in user.get('display_name',''):
the above answer will not work if the key is present and its value in None
so i updated my answer according to @tobias_k comment -
if query in (user['display_name'] or ''):
It would seem that at least one of your display_name
values is None.
When you use the in
keyword in that case, you're looking for something in None
, which throws an exception.
Depending on how you wanted to handle that case, you could check if the value exists before trying to append.
for user in users:
if user and user['display_name'] and query in user['display_name']: # probably extract this check into a helper
result_set.append(user)
I would extract the Boolean logic into a separate method:
def is_query_match(user, query):
if user and user['d'] and query in user['d']:
return True
return False
So you could then use:
for user in users:
if is_query_match(user, query):
result_set.append(user)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.