[Python] Best way to get a single key from a dictionary?

Discussão em 'Python' iniciado por Stack, Setembro 5, 2025.

  1. Stack

    Stack Membro Participativo

    Having a python dictionary and knowing it is made of just one key/value pair, what's the best way to retrieve that single/unique item?

    So far I know I could use one of these two ways:


    1. list(mydict.keys())[0] (same as list(mydict)[0])


    2. next(iter(mydict.keys())) (same as next(iter(mydict)))

    As far as I understand, list performances are worse than iter ones so the latter approach should be better, right? Which ways is best? There's something that's even better than the two way I indicated? Please let me know.

    Continue reading...

Compartilhe esta Página