The Python Oracle

How can I extract all values from a dictionary in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
00:33 Accepted answer (Score 434)
01:16 Answer 2 (Score 63)
01:29 Answer 3 (Score 54)
01:42 Answer 4 (Score 17)
02:27 Thank you

--

Full question
https://stackoverflow.com/questions/7002...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary #extract

#avk47



ACCEPTED ANSWER

Score 449


If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].




ANSWER 2

Score 71


Use values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]



ANSWER 3

Score 19


For nested dicts, lists of dicts, and dicts of listed dicts, ... you can use

from typing import Iterable

def get_all_values(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from get_all_values(v)
    elif isinstance(d, Iterable) and not isinstance(d, str): # or list, set, ... only
        for v in d:
            yield from get_all_values(v)
    else:
        yield d 

An example:

d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': set([6, 7])}], 'f': 'string'}
list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7, 'string']

Big thanks to @vicent for pointing out that strings are also Iterable! I updated my answer accordingly.

PS: Yes, I love yield. ;-)




ANSWER 4

Score 18


Call the values() method on the dict.