How can I get a list of the values in a dict in Python?
In Java, getting the values of a Map as a List is as easy as doing list = map.values();
. I'm wondering if there is a similarly simple way in Python to get a list of values from a dict.
Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.
So we have to get the dictionaries present in the list according to the key. We can get this by using dict. items().
To get a list of all keys from a dictionary, you can simply use the dict. keys() function.
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
dict.values
returns a view of the dictionary's values, so you have to wrap it in list
:
list(d.values())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With