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
?
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
Call the values()
method on the dict.
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])
Use values()
>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}
>>> d.values()
<<< [-0.3246, -0.9185, -3985]
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
. ;-)
For Python 3, you need:
list_of_dict_values = list(dict_name.values())