【问题标题】:Constructing Dictionaries of dictionary in python在python中构造字典的字典
【发布时间】:2017-09-04 09:48:30
【问题描述】:
def home(request):
    context = populate_user_context(request, user.username)   

    val=amqp.consumer() 

    return render(request, "home.html", context, "Content-type:text/HTML", 200, None)



def populate_user_context(request,username):
    user = User.objects.get(username=username)
    context={'first_name':(user.first_name or None),
         'last_name':(user.last_name or None),
         'email':(user.email or None)
         }
    return context 

当调用 home 函数时。它建立上下文然后调用消费者函数。消费者函数返回一个字典。如果它返回一个字典,那么我应该再次调用它,直到它没有返回(这部分还没有编码)。最后我必须将它添加到上下文并渲染到 home.html。

每个字典就像 {'a' : val1, 'b': val2}。因为我不知道它可能返回多少字典。将字典添加到上下文并呈现到 home.html 页面的最佳方法是什么。 之前的问题不清楚,所以我已经编辑了。

【问题讨论】:

  • 我想构建像{{"a":val1,"b":val2}, {"a":val1,"b":val2}}这样的字典 - 这不是字典。
  • @Ahsanul Haque 是对的,那是一套字典。请更具体
  • 什么for循环?显示minimal reproducible example
  • 也许你想要的是一个字典列表

标签: python django


【解决方案1】:

对于字典,您缺少键,除非您想创建一个列表(在这种情况下,您使用了错误的括号)。

列表:

x = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]

字典:

x= {"one": {"a": 1, "b": 2}, "two": {"a": 3,"b": 4}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2020-05-02
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多