当我从同一个函数中获取键和值时,使用字典理解构建一个dict
假设我有一个复杂的函数get_stuff,它接受一个 int 并返回一个元组,第一个元素的类型是 str。下面的示例具有相同的行为,但假设实际函数更复杂并且不能轻易地一分为二:
def get_stuff(x):
return str(5*x),float(3*x)
我想要的是构建一个 dict,其 (key,value) 对是在特定整数集上调用时 get_stuff 的结果。一种方法是:
def get_the_dict(set_of_integers):
result = {}
for i in set_of_integers:
k,v = get_stuff(i)
result[k] = v
return result
我宁愿为此使用 dict comprehension,但我不知道是否可以在理解中拆分该对以分别捕获键和值。
def get_the_dict_with_comprehension(set_of_integers):
return {get_stuff(i) for i in set_of_integers} #of course this doesn't work
我怎样才能做到这一点?
回答
你可以这样做,而不是完全字典理解:
dict(get_stuff(i) for i in range(10))