I have a function which can return a variable number of outputs. I would like to save this to a dictionary like so:
val_dict={}
idx = 0
for key in some_test_function(1,2,3):
val_dict[idx] = key
idx +=1
Now while this thing does work, I was wondering if there is a more elegant way of doing it. Any ideas?
You can use the enumerate()
function to add the indices in the dictionary:
val_dict = dict(enumerate(some_test_function(1, 2, 3)))
This gives you the exact same integer index to value mapping. However, just a list would give you the exact same index-to-value mapping:
val_list = list(some_test_function(1, 2, 3))
(if some_test_function
already returns a list
object, just remove the list()
call).
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.