Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best and Fastest way to get first value from dictionary values

What is the fastest and best way to get first value from dictionary values? There are multiple techniques, but what is the best (memory and speed) and why?

Examples below. I would be grateful for other techniques as well:

dictis = {
    1: "One"
    , 2: "Two"
    , 3: "Three"
    , 4: "Four"
}

# 1 technique:
#----------------

value = next(iter(dictis.values()))
print(value)

# 2 technique:
#----------------

value = list(dictis.values())[0]
print(value)

# 3 technique:
#----------------

value = [value for value in dictis.values()][0]
print(value)

# 4 technique:
#----------------

value = next(value for value in dictis.values())
print(value)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For sure second and third way is bad as it create full list so consumes O(n) memory and will be slower for big dictionaries.

But why don’t measure them by yourself?

import timeit

code = """
dictis = {1: "One", 2: "Two", 3: "Three", 4: "Four"}
value = next(iter(dictis.values()))
"""
code2 = """
dictis = {1: "One", 2: "Two", 3: "Three", 4: "Four"}
value = list(dictis.values())[0]
"""
code3 = """
dictis = {1: "One", 2: "Two", 3: "Three", 4: "Four"}
value = [value for value in dictis.values()][0]
"""
code4 = """
dictis = {1: "One", 2: "Two", 3: "Three", 4: "Four"}
value = next(value for value in dictis.values())
"""

time = timeit.timeit(code)
print("code1: ", time) # 0.31126813999999997
time = timeit.timeit(code2)
print("code2: ", time) # 0.397324552
time = timeit.timeit(code3)
print("code3: ", time) # 0.514635408
time = timeit.timeit(code4)
print("code4: ", time) # 0.6130763850000001

Tested for dictis = {i: str(i) for i in range(1000)} few times as well, results:

code1:  2.455605702
code2:  2.525566626
code3:  2.7503477000000007
code4:  2.551036469999999

So conclusion is the first approach is the fastest at least for that specific case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading