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?
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?
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): # 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])}]}
list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7]
PS: Yes, I love yield. ;-)
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
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]
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])
Normal Dict.values()
will return something like this
dict_values(['value1'])
dict_values(['value2'])
If you want only Values use
list(Dict.values())[0] # Under the List