692

How can I get a list of the values in a dict in Python?

In Java, getting the values of a Map as a List is as easy as doing list = map.values();. I'm wondering if there is a similarly simple way in Python to get a list of values from a dict.

0

7 Answers 7

1067

dict.values returns a view of the dictionary's values, so you have to wrap it in list:

list(d.values()) 
Sign up to request clarification or add additional context in comments.

4 Comments

iter(d.values()) returns an iterator of the dictionary values in Python 3, which doesn't immediately consume memory.
@Peterino Yes though in python 3 it would be very rare that you'd need to explicitly invoke iter(d.values()). You can just simply iterate the values: for value in d.values(): which by the way, is what everyone would probably be doing in most practical use cases. Usually you don't need a list of dictionary values just for the sake of having a list like in this question. A lot of these Python 2 comments I made are almost useless now and maybe confusing for Python 3 programmers who read this now
@jamylak: Take this use case: An API wants to return the values of a dictionary. Here you won't iterate (unless you use list or generator comprehensions), you'll apply list() or iter(), depending on your preference and further processing.
@Peterino Fair enough
115

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'] 

3 Comments

which one is faster?
@BigChief Some timings were posted here stackoverflow.com/a/56736691/1219006 I didn't yet validate them but maybe that helps answer your question. I think what really matters here is clarity over raw speed
ah very interesting just in general the finding is that unpacking is faster for smaller collections and converting to list for bigger ones
78

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 Build ipython 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

1 Comment

Thanks for sharing the benchmark. So just a small update: On Apple Silicon with Python 3.10 and for big dicts, there is no difference (any more).
20

Follow the below example --

songs = [ {"title": "happy birthday", "playcount": 4}, {"title": "AC/DC", "playcount": 2}, {"title": "Billie Jean", "playcount": 6}, {"title": "Human Touch", "playcount": 3} ] print("====================") print(f'Songs --> {songs} \n') title = list(map(lambda x : x['title'], songs)) print(f'Print Title --> {title}') playcount = list(map(lambda x : x['playcount'], songs)) print(f'Print Playcount --> {playcount}') print (f'Print Sorted playcount --> {sorted(playcount)}') # Aliter - print(sorted(list(map(lambda x: x['playcount'],songs)))) 

Comments

4

If you need to assign the values as a list to a variable, another method using the unpacking * operator is

*values, = d.values() 
Get a list of values of specific keys in a dictionary

Most straightforward way is to use a comprehension by iterating over list_of_keys. If list_of_keys includes keys that are not keys of d, .get() method may be used to return a default value (None by default but can be changed).

res = [d[k] for k in list_of_keys] # or res = [d.get(k) for k in list_of_keys] 

As often the case, there's a method built into Python that can get the values under keys: itemgetter() from the built-in operator module.

from operator import itemgetter res = list(itemgetter(*list_of_keys)(d)) 

Demonstration:

d = {'a':2, 'b':4, 'c':7} list_of_keys = ['a','c'] print([d.get(k) for k in list_of_keys]) print(list(itemgetter(*list_of_keys)(d))) # [2, 7] # [2, 7] 
Get values of the same key from a list of dictionaries

Again, a comprehension works here (iterating over list of dictionaries). As does mapping itemgetter() over the list to get the values of specific key(s).

list_of_dicts = [ {"title": "A", "body": "AA"}, {"title": "B", "body": "BB"} ] list_comp = [d['title'] for d in list_of_dicts] itmgetter = list(map(itemgetter('title'), list_of_dicts)) print(list_comp) print(itmgetter) # ['A', 'B'] # ['A', 'B'] 

Comments

0

If you want return a list by default (as in python 2) instead of a view, one can create a new dict class and overwrite the values method:

class ldict(dict): # return a simple list instead of dict_values object values = lambda _: [*super().values()] d = ldict({'a': 1, 'b': 2}) d.values() # [1, 2] (instead of dict_values([1, 2])) 

Comments

-4
out: dict_values([{1:a, 2:b}]) in: str(dict.values())[14:-3] out: 1:a, 2:b 

Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.