【发布时间】:2020-12-16 05:22:14
【问题描述】:
我正在编写一个函数,它返回两个值,这将形成字典的键值对。此函数将用于创建具有字典理解的字典。但是,使用字典理解需要以“键:值”格式提供一对值。为此,我必须调用该函数两次。一次用于键,一次用于值。例如,
sample_list = [['John', '24', 'M', 'English'],
['Jeanne', '21', 'F', 'French'],
['Yuhanna', '22', 'M', 'Arabic']]
def key_value_creator(sample_list):
key = sample_list[0]
value = {'age': sample_list[1],
'gender': sample_list[2],
'lang': sample_list[3]}
return key, value
dictionary = {key_value_creator(item)[0]: \
key_value_creator(item)[1] for item in sample_list}
如您所见,该函数被调用两次以生成可以在一次运行中生成的值。有没有办法以理解可以使用的格式返回值?如果可能,该函数只需要调用一次,如下所示:
dictionary = {key_value_creator(item) for item in sample_list}
据我所见,返回多个值的其他方式是以字典或列表的形式返回,
return {'key': key, 'value': value}
return [key, value]
但无论哪种方式,要访问它们,我们都必须调用该函数两次。
dictionary = {key_value_creator(item)['key']: \
key_value_creator(item)['value'] for item in sample_list}
dictionary = {key_value_creator(item)[0]: \
key_value_creator(item)[1] for item in sample_list}
有没有办法格式化这些值,以便我们可以将它们以所需的格式发送到字典理解语句?
编辑: 预期输出:
{ 'John': {'age': '24', 'gender': 'M', 'lang': 'English'},
'Jeanne': {'age': '21', 'gender': 'F', 'lang': 'French'},
'Yuhanna': {'age': '22', 'gender': 'M', 'lang': 'Arabic'}}
【问题讨论】:
-
你能发布预期的输出吗
标签: python dictionary return dictionary-comprehension