random choice from dictionary

Chris Angelico rosuav at gmail.com
Sun Dec 23 03:37:16 EST 2018


On Sun, Dec 23, 2018 at 7:34 PM Abdur-Rahmaan Janhangeer
<arj.python at gmail.com> wrote:
>
> greetings,
>
> just a check, is this:
>
> random.choice(list(data.keys()))
>
> the only way to get a random key from a dictionary? if not any plan to a
> more convenient naming?

Does it have to be truly random, or are you okay with it being
arbitrary selected? Dictionaries have a popitem method that may be of
value. Otherwise, I would say what you have is fine, save that I'd
just write random.choice(list(data)) instead of using the unnecessary
keys() call.

ChrisA



More information about the Python-list mailing list