python - 如何创建这个嵌套的Python字典?

标签 python django

这就是我想要的(警告:Python菜鸟,这可能是一种不正确的表示方式,但我希望你得到我想要的)

forms = { 
            { 'id' : '1',
              'form' : form_something,
            },
            { 'id'  : '4',
              'form' : form_something2,
            }
        }  

现在我的问题是如何在我的 django View 中创建这个字典,到目前为止,它是这样的->

links = Links.objects.all()
forms = {}

for link in links:
    form = LinkForm(instance = link )
    forms.update({ 'id' : link.id, 'form' : form})
    # which is obviously the wrong way to do it

最佳答案

这将创建一个字典列表:

links = Links.objects.all()
forms = []
for link in links:
    form = LinkForm(instance = link)
    forms.append({'id': link.id, 'form': form})

如果你想创建一个字典的字典,你必须有键:

links = Links.objects.all()
forms = {}
for link in links:
    form = LinkForm(instance = link)
    # you need something to use as a key
    forms[key] = {'id': link.id, 'form': form}

请注意,我更改了代码中的空格位置以匹配标准 Python 方式,但这并不重要。

嵌套字典的形式为:

forms = { 
       'key1': { 'id' : '1',
          'form' : form_something,
        },
       'key2': { 'id'  : '4',
          'form' : form_something2
        }
    }  

我添加了键并删除了 form_something2 之后的逗号。

关于python - 如何创建这个嵌套的Python字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799318/

相关文章:

python - 在opencv python中使用CV_CAP_PROP_POS_FRAMES从视频中获取帧

python - 关于在 python CGI 中获取客户端 ip 地址

模板中的 django 分页 <if current page>

django - Django 是否原生支持迁移

python - models.py 中的 models.Model 参数到底指的是什么?

python - 在更新 Redux 状态之前规范化来自服务器的 JSON 响应

python - 如何在 python 中使用 nosetests 同时传递/接受 argparse 的参数?

python - 考虑到随着 n 的增加,内存需求也迅速增加,人们如何使用 n-gram 进行情感分析?

python - Sage 5.0 令人困惑的语法错误

Django + AWS s3 可以上传文件但不能访问它们