Ich kann mir vier Möglichkeiten vorstellen (es kann mehr sein).
Code: Select all
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")
Code: Select all
func1 duration=0.6322s
func2 duration=0.8306s
func3 duration=0.5505s
func4 duration=0.5040s