I have following objects
a = ("one", 1)
b = ("two", 2)
c = ("seven", 7)
my_dict = {10: a, 20:b, 70:c}
I want to get a list of [1, 2, 7]
from my_dict
. Whats the most pythonic way to do so?
Just use list comprehension. It's the most pythonic way of doing most things;)
output = [x[1] for x in my_dict.values()]
If you like the functional way, you could use:
list(zip(*my_dict.values()))[1]
Output: (1, 2, 7)
Or, as list:
list(list(zip(*my_dict.values()))[1])
Output: [1, 2, 7]
You can use tuple unpacking inside the list comprehension to avoid having to index into the tuple:
result = [item for _, item in my_dict.values()]
print(result)
This prints:
[1, 2, 7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.