How to extract all values from a dictionary in Python?
Asked Answered
N

15

267

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?

Negron answered 9/8, 2011 at 20:22 Comment(0)
O
448

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

Onagraceous answered 9/8, 2011 at 20:23 Comment(1)
If you are using Python 3 you'll want to use list(your_dict.values()) to get a list (and not a dict_values object).Integrity
E
70

Use values()

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

>>> d.values()
<<< [-0.3246, -0.9185, -3985]
Exhibitionism answered 9/8, 2011 at 20:23 Comment(0)
K
65

For Python 3, you need:

list_of_dict_values = list(dict_name.values())
Kamseen answered 24/4, 2020 at 11:18 Comment(5)
Thank You for mentioning that method list() is neededTeleprinter
this is mandatory for accessing the elements using indicesInmesh
Actually, dict_name.values().tolist should be faster if you are having 1d Array, check this hereBlume
@hozayfa-el-rifai That's for numpy only. {}.values().tolist() doesn't work.Cervicitis
@TedBrownlow not sure what i was trying to prove here, but yeah you are right!Blume
F
18

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. ;-)

Farman answered 23/6, 2019 at 8:26 Comment(2)
This is pretty much exactly what I was looking for. Note that strings are also iterable. In my use case the values in my dictionary were also string so I would run into an error about recursive depth reached. To fix, I did ``` def get_all_values(d): if isinstance(d, dict): for v in d.values(): yield from get_all_values(v) elif isinstance(d, typing.Iterable) and not isinstance(d, str): # or list, set, ... only for v in d: yield from get_all_values(v) else: yield d ```Triumph
Thanks a lot for pointing out that issue. You are completely right! I updated my answer!Farman
U
17

Call the values() method on the dict.

Uxoricide answered 9/8, 2011 at 20:23 Comment(0)
A
17

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()
Azeria answered 9/8, 2011 at 20:25 Comment(0)
N
8

I know this question been asked years ago but its quite relevant even today.

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}
>>> l = list(d.values())
>>> l
[-0.3246, -0.9185, -3985]
Nonrepresentational answered 22/3, 2022 at 17:24 Comment(0)
F
6

If you want all of the values, use this:

dict_name_goes_here.values()
Foret answered 28/7, 2017 at 15:16 Comment(0)
B
5

Code of python file containing dictionary

dict={"Car":"Lamborghini","Mobile":"iPhone"}
print(dict)

If you want to print only values (instead of key) then you can use :

dict={"Car":"Lamborghini","Mobile":"iPhone"}
for thevalue in dict.values():
    print(thevalue)

This will print only values instead of key from dictionary

Bonus : If there is a dictionary in which values are stored in list and if you want to print values only on new line , then you can use :

dict={"Car":["Lamborghini","BMW","Mercedes"],"Mobile":["Iphone","OnePlus","Samsung"]}
nd = [value[i] for value in dict.values()
         for i in range(2)]
print(*nd,sep="\n")

Reference - Narendra Dwivedi - Extract Only Values From Dictionary

Buckhound answered 25/1, 2022 at 12:52 Comment(0)
M
3
d = <dict>
values = d.values()
Monovalent answered 9/8, 2011 at 20:24 Comment(0)
L
3

To see the keys:

for key in d.keys():
    print(key)

To get the values that each key is referencing:

for key in d.keys():
    print(d[key])

Add to a list:

for key in d.keys():
    mylist.append(d[key])
Lorgnon answered 8/5, 2018 at 14:8 Comment(2)
list comprehension can help as wellCystolith
list=[d[key] for key in d.keys()]Cystolith
J
0

Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.

Juxon answered 19/4, 2017 at 12:5 Comment(0)
E
0
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
Examination answered 6/7, 2019 at 10:49 Comment(1)
as pointed in the answer by Faaiz Qadri, you need to wrap you solution inside list() otherwise it returns dict_valuesSmarmy
C
0

You can use items(), keys() and values() to get both the keys and values, only the keys and only the values in a dictionary respectively as shown below:

person = {'name':'John', 'age':35, 'gender':'Male'}

print(person.items()) # dict_items([('name', 'John'), ('age', 35)])
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['John', 35])

And, you can iterate items(), keys() and values() with for loop as shown below:

person = {'name':'John', 'age':35}

for key, value in person.items(): # name John
    print(key, value)             # age 35
    
for key in person.keys(): # name
    print(key)            # age
    
for value in person.values(): # John
    print(value)              # 35

But, you cannot access items(), keys() and values() with [] as shown below because there are errors:

person = {'name':'John', 'age':35}

print(person.items()[0]) # Error
print(person.keys()[0]) # Error
print(person.values()[0]) # Error

But, if using list(), you can access them with [] as shown below:

person = {'name':'John', 'age':35}

print(list(person.items())[0]) # ('name', 'John')
print(list(person.keys())[0]) # name
print(list(person.values())[0]) # John
Carlsen answered 15/5, 2023 at 1:38 Comment(0)
C
-1

Normal Dict.values()

will return something like this

dict_values(['value1'])

dict_values(['value2'])

If you want only Values use

  • Use this

list(Dict.values())[0] # Under the List

Crossed answered 18/2, 2021 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.