如何遍历一个字典

时间:2015-08-20 12:10:22

标签: python django

我想在模板表中显示这段数据

{u'User1': {'annual_spend__sum': None}, u'User2': {'annual_spend__sum': 80}, u'User3': {'annual_spend__sum': 30}, u'User4': {'annual_spend__sum': None}}

我不确定如何循环显示数据以便任何人都能正确显示?

this_user = User.objects.get(id=3)
    all_users = User.objects.all()
    values = {}
    for this_user in all_users:
        values[this_user.username] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='CV').aggregate(Sum('annual_spend'))
    values.items()


    return render(request, 'index.html', {'annual_spend': values})

更新

def func(request):
    from django.template import context
    this_user = User.objects.get(id=3)
    all_users = User.objects.all()

    values = {}
    for this_user in all_users:
        values[this_user.username] = Lead.objects.filter(assign_to=this_user).exclude(lead_status='CV').aggregate(Sum('annual_spend'))

    context = {}
    annual_spend__sum_list = []
    data = values

    for i in data:
        annual_spend__sum_list.append(data[i]['annual_spend__sum'])

    context['result'] = annual_spend__sum_list

    return render(request, "index.html", context)

模板

<ul>
{% for i in result %}
<li>{{ i }}</li>
{% endfor %}
</ul>

1 个答案:

答案 0 :(得分:-1)

像任何其他词典一样迭代它。

data = {'User1': {'annual_spend__sum': None}, 'User2': {'annual_spend__sum': 80}, 'User3': {'annual_spend__sum': 30}, 'User4': {'annual_spend__sum': None}}

for i in data:
    print i, data[i], data[i]['annual_spend__sum']

这是输出:

>>> data = {'User1': {'annual_spend__sum': None}, 'User2': {'annual_spend__sum': 80}, 'User3': {'annual_spend__sum': 30}, 'User4': {'annual_spend__sum': None}}
>>> 
>>> for i in data:
...     print i, data[i], data[i]['annual_spend__sum']
... 
User4 {'annual_spend__sum': None} None
User2 {'annual_spend__sum': 80} 80
User3 {'annual_spend__sum': 30} 30
User1 {'annual_spend__sum': None} None
>>> 

现在,你可以用它做任何你想做的事。

我建议您制作一个上下文字典并在其中加list annual_spend__sum,然后将其传递给render

这样做:

def func(request):
    context = {}
    annual_spend__sum_list = []
    data = {'User1': {'annual_spend__sum': None}, 'User2': {'annual_spend__sum': 80}, 'User3': {'annual_spend__sum': 30}, 'User4': {'annual_spend__sum': None}}

    for i in data:
        annual_spend__sum_list.append(data[i]['annual_spend__sum'])

    context['result'] = annual_spend__sum_list

    return render(request, "index.html", context)

现在,在index.html中你可以这样打印:

<ul>
    {% for i in result %}
        <li>{{ i }}</li>
    {% endfor %}
</ul>

你可以通过很多不同的方式来做到这一点。这是最基本和最容易解释的。参见for循环,我直接引用了密钥并迭代了结果。