On 29/06/2020 20:19, Rhodri James wrote:
On 29/06/2020 18:42, Stestagg wrote:
Several times now, I've had the need to 'just get any key/value' from a
large dictionary.  I usually try first to run `var.keys()[0]` only to be
told that I'm not allowed to do this, and instead have to ask python to
make a copy of this datastructure with a different type, just so I can
perform the index operation.  This is possible, but seems redundant, and
reinforces bad practices around creating copies of potentially large
structures.

You can do

>>> first_key = next(iter(my_dict.keys()))

but I agree, it's not a particularly obvious way to proceed.

You can do (as I on occasion have):
    for first_key in my_dict: break
Or if you need the value as well:
    for first_key in my_dict:
        first_value = my_dict[first_key]
        break

(NB Whatever method you use, beware the case of the dictionary being empty!)
_______________________________________________
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/BJWWFQSCCWJTXP6UQWFBE2WDDXTNQ3JD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to