How can I get list of values from dict? How can I get list of values from dict? python python

How can I get list of values from dict?


Yes it's the exact same thing in Python 2:

d.values()

In Python 3 (where dict.values returns a view of the dictionary’s values instead):

list(d.values())


You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}>>> [*d.values()]['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}>>> list(d.values())['a', 'b']


There should be one ‒ and preferably only one ‒ obvious way to do it.

Therefore list(dictionary.values()) is the one way.

Yet, considering Python3, what is quicker?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}small_df = {x: float(x+42) for x in range(10)}print('Small Dict(str)')%timeit [*small_ds.values()]%timeit [].extend(small_ds.values())%timeit list(small_ds.values())print('Small Dict(float)')%timeit [*small_df.values()]%timeit [].extend(small_df.values())%timeit list(small_df.values())big_ds = {x: str(x+42) for x in range(1000000)}big_df = {x: float(x+42) for x in range(1000000)}print('Big Dict(str)')%timeit [*big_ds.values()]%timeit [].extend(big_ds.values())%timeit list(big_ds.values())print('Big Dict(float)')%timeit [*big_df.values()]%timeit [].extend(big_df.values())%timeit list(big_df.values())
Small Dict(str)256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)Small Dict(float)268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)Big Dict(str)17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)Big Dict(float)13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name                    Version                   Buildipython                   7.5.0            py37h24bf2e0_0

The result

  1. For small dictionaries * operator is quicker
  2. For big dictionaries where it matters list() is maybe slightly quicker