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

Posted on

Question :

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

I have a dictionary d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}.

How do I extract all of the values of d into a list l?

Answer #1:

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), ...].

Answered By: Pierre Bourdon

Answer #2:

Use values()

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

>>> d.values()
<<< [-0.3246, -0.9185, -3985]
Answered By: zeekay

Answer #3:

If you want all of the values, use this:

dict_name_goes_here.values()

If you want all of the keys, use this:

dict_name_goes_here.keys()

IF you want all of the items (both keys and values), I would use this:

dict_name_goes_here.items()
Answered By: Tyler Crompton

Answer #4:

For Python 3, you need:

list_of_dict_values = list(dict_name.values())
Answered By: Faaiz Qadri

Answer #5:

Call the values() method on the dict.

Answered By: David Heffernan

Answer #6:

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

def get_all_values(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from get_all_values(v)
    elif isinstance(d, list):
        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': 6}]}

list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]

PS: I love yield. 😉

Answered By: Michael Dorner

Answer #7:

If you want all of the values, use this:

dict_name_goes_here.values()
Answered By: Govind Sagar

Answer #8:

d = <dict>
values = d.values()
Answered By: Gabriel Ross

Leave a Reply

Your email address will not be published. Required fields are marked *