加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何使用python自动创建词典?

发布时间:2020-12-20 12:14:18 所属栏目:Python 来源:网络整理
导读:我正在做一个初学者 Python课程,目的是制作一堆词典. Create three dictionaries: lloyd,alice,and tyler. Give each dictionary the keys “name”,“homework”,“quizzes”,and “tests”. Have the “name” key be the name of the student (that is,ll
我正在做一个初学者 Python课程,目的是制作一堆词典.

  1. Create three dictionaries: lloyd,alice,and tyler.

Give each dictionary the keys “name”,“homework”,“quizzes”,and
“tests”.

Have the “name” key be the name of the student (that is,lloyd’s name
should be “Lloyd”) and the other keys should be an empty list (We’ll
fill in these lists soon!)

我通过执行以下操作来完成此操作:

def make_dict(list_of_names):
  for names in list_of_names:
    names = {
      "name": names,"homework" : [],"quizzes" : [],"tests" : []
  }

list_of_names = ["lloyd",'alice','tyler']

make_dict(list_of_names)

为什么这不起作用?它应该工作,只是Codeacademy开发区域不允许这个工作吗?我意识到我有点多余,而且我可以非常直接地做到这一点,并故意在我如何做到这一点上发挥创意.

在任何情况下,基于输入列表制作字典的自动化方法是什么?

解决方法

你在每个循环中创建一个名为names的字典,但实际上并没有用它做任何事情 –

def make_dict(list_of_names):
    results = []
    for names in list_of_names:
        names = {
            "name": names,"tests" : []
        }
        results.append(names)
    return results

list_of_names = ["lloyd",'tyler']

my_dicts = make_dict(list_of_names)

这会跟踪您创建的名称,然后在最后将它们提供给您.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读