使用循环,从列表创建字典

我正在尝试创建一个函数来创建一个字典,给出一个将被输入的列表。我认为通过使用 for 循环,我可以获取列表,创建键,然后使用循环输入列表中每个项目的值。


使用此列表作为输入:


simpsons = 'Homer', 'Bart', 'Marge', 'Lisa'


def create_dict_from_list(names):

    name_dict = {}

    for name in names:

        name_dict['name']= name

    return name_dict

这仅返回一个键值对。看起来字典不会创建多个值,这就是为什么它只返回一个而不遍历列表的其余部分。


当我更改时name_dict[name] = name,它将创建所有键、值,但键和值都是名称。


当我更改时name_dict[name] = 'name',我得到键值反转,但它返回列表中的所有 4 个项目。


MMMHUHU
浏览 339回答 2
2回答

ibeautiful

对于您想要的答案(基于我对您问题的理解),我不确定您为什么使用 for 循环。您的函数中不需要 for 循环。只需一个简单的任务即可完成这项工作。你不必要地把它复杂化了。simpsons = ['Homer', 'Bart', 'Marge', 'Lisa']def create_dict_from_list(names):&nbsp; &nbsp; name_dict = {}&nbsp; &nbsp; name_dict['name'] = names # <--- No need of for loop&nbsp; &nbsp; return name_dictcreate_dict_from_list(simpsons)# {'name': ['Homer', 'Bart', 'Marge', 'Lisa']}

繁花如伊

您可以将默认值设置[]为键的空列表'name' 对于给定的示例,for如果要将所有名称分配给键,则可以不使用循环(如@Bazingaa 所回答)'name'。另一方面,如果您想有选择地分配名称,请使用for循环。simpsons = 'Homer', 'Bart', 'Marge', 'Lisa'def create_dict_from_list(names):&nbsp; &nbsp; name_dict = {}&nbsp; &nbsp; name_dict.setdefault('name',[])&nbsp; &nbsp; for name in names:&nbsp; &nbsp; &nbsp; &nbsp; name_dict['name'].append(name)&nbsp; &nbsp; return name_dictcreate_dict_from_list(simpsons)输出{'name': ['Homer', 'Bart', 'Marge', 'Lisa']}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python