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!)