[Python] Efficient extraction of first/only key in a dictionary

Discussão em 'Python' iniciado por Stack, Julho 27, 2025.

  1. Stack

    Stack Membro Participativo

    Assumption is that we have a dictionary containing exactly one key/value pair. Objective is to extract the only key.

    I can think of four ways to do this (there may be more).

    import timeit


    def func1(d):
    """
    Convert to a list and return the first element
    """
    return list(d)[0]


    def func2(d):
    """
    Unpack
    """
    rv, *_ = d
    return rv


    def func3(d):
    """
    Classic efficient approach
    """
    return next(iter(d))


    def func4(d):
    """
    Appears to be faster than the classic approach
    """
    for key in d:
    return key


    if __name__ == "__main__":
    d = {"foo": 0}
    for func in (func1, func2, func3, func4):
    assert func1(d) == func(d)
    duration = timeit.timeit(lambda: func(d), number=5_000_000)
    print(func.__name__, f"{duration=:.4f}s")


    Output:

    func1 duration=0.6322s
    func2 duration=0.8306s
    func3 duration=0.5505s
    func4 duration=0.5040s


    I have always understood that the implementation in func3() is optimal - and that's what I would normally use.

    However, it appears that func4() is more efficient. This may be related to Python version (3.13.5 in this case).

    Why would func4() perform better than func3()? Are there optimisations in modern Python versions that would affect this?

    Continue reading...

Compartilhe esta Página