In its current implementation, the list type does not provide a simple and
straightforward way to retrieve one of its elements that fits a certain
criteria.
If you had to get the user where user['id'] == 2 from this list of users, for
example, how would you do it?
users = [
{'id': 1,'name': 'john'},
{'id': 2, 'name': 'anna'},
{'id': 3, 'name': 'bruce'},
]
# way too verbose and not pythonic
ids = [user['id'] for user in users]
index = ids.index(2)
user_2 = users[index]
# short, but it feels a bit janky
user_2 = next((user for user in users if user['id'] == 2), None)
# this is okay-ish, i guess
users_dict = {user['id']: user for user in users}
user_2 = users_dict.get(2)
In my opinion, the list type could have something along these lines:
class MyList(list):
def find(self, func, default=None):
for i in self:
if func(i):
return i
return default
my_list = MyList(users)
user_2 = my_list.find(lambda user: user['id'] == 2)
print(user_2) # {'id': 2, 'name': 'anna'}
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/3ZOLBF3TWGLIHO6LRS57I4OO5UISFGMO/
Code of Conduct: http://python.org/psf/codeofconduct/