close

How to get single value from dict with single entry?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get single value from dict with single entry in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get single value from dict with single entry?

  1. How to get single value from dict with single entry?

    list(d.values())[0] will be evaluated to 1. As pointed out in the comments, the cast to list is only needed in python3.

  2. get single value from dict with single entry

    list(d.values())[0] will be evaluated to 1. As pointed out in the comments, the cast to list is only needed in python3.

Method 1

list(d.values())[0] will be evaluated to 1. As pointed out in the comments, the cast to list is only needed in python3.

next(iter(d.values())) is another possibility (probably more memory efficient, as you do not need to create a list)

Both solution testes locally with python 3.6.0 and in TIO with python 2.

Method 2

next(iter(d.values())) is the natural way to extract the only value from a dictionary. Conversion to list just to extract the only element is not necessary.

It is also performs best of the available options (tested on Python 3.6):

d = [{'a': i} for i in range(100000)]

%timeit [next(iter(i.values())) for i in d]  # 50.1 ms per loop
%timeit [list(i.values())[0] for i in d]     # 54.8 ms per loop
%timeit [list(i.values()).pop() for i in d]  # 81.8 ms per loop

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read