On Sat, May 07, 2022 at 04:01:34AM -0000, python-id...@lucas.rs wrote:

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

user = None
for record in users:
    if record['id'] == 2:
        user = record
        break
else:  # for...else
    raise LookupError('user id not found')

If I needed to do it more than once, or if it needed testing, I would 
change the break into `return record` and put it into a function.

If I really needed to lookup user IDs a lot, I wouldn't use a list, I 
would use something like this:

    users = { # map user ID to user name
        1: 'john',
        2: 'anna',
        3: 'bruce',
        }

so that user ID lookups are simple and blazingly fast:

    user = users[2]

rather than needing to walk through the entire list inspecting each 
item. Picking the right data structure for your problem is 9/10th of the 
battle.


> # way too verbose and not pythonic
> ids = [user['id'] for user in users]
> index = ids.index(2)
> user_2 = users[index]

Three lines is not "too verbose". I wouldn't call it "not Pythonic", I 
would just call it poor code that does too much unnecessary work.


> # short, but it feels a bit janky
> user_2 = next((user for user in users if user['id'] == 2), None)

Seems OK to me.


> # this is okay-ish, i guess
> users_dict = {user['id']: user for user in users}
> user_2 = users_dict.get(2)

More unnecessary work, building an entire temporary dict of potentially 
millions of users just to extract one. Of course if you are going to be 
using it over and over again, this is the right solution, not the list.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PG32UB5DLF7SDPHSECYT6L4PDQW3D35I/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to