【问题标题】:How to iterate over list of dictionary in python?如何遍历python中的字典列表?
【发布时间】:2012-07-07 10:14:24
【问题描述】:

我在 python 中有一个list of dictionary,即

listofobs = [{'timestamp': datetime.datetime(2012, 7, 6, 12, 39, 52), 'ip': u'1.4.128.0', 'user': u'lovestone'}, {'timestamp': datetime.datetime(2012, 7, 6, 12, 40, 32), 'ip': u'192.168.21.45', 'user': u'b'}]

我想在 Django 模板中使用 listofobs 变量的所有键和值。例如:

第一次迭代:

timestamp = 7 july 2012, 12:39 Am
ip = 1.4.128.0
user = lovestone

第二次迭代:

 timestamp = 7 july 2012, 12:40 Am
 ip =  192.168.21.45
 user = b

等等..

【问题讨论】:

    标签: python django django-templates python-2.7


    【解决方案1】:
    for a in listofobs:
        print str( a['timestamp'] ), a['ip'], a['user']
    

    将遍历字典列表,然后在模板中使用它们,只需将其包装在所需的 django 语法中,这与常规 python 非常相似。

    【讨论】:

      【解决方案2】:

      Django 模板语法可以让你遍历一个字典列表:

      {% for obj in listofobjs %}
          timestamp = {{ obj.timestamp }}
          ip = {{ obj.ip }}
          user = {{ obj.user }}
      {% endfor %}
      

      您只需确保 listofobjs 在您的上下文中进行渲染。

      【讨论】:

        【解决方案3】:

        查看built in for template tag 的示例。

        循环项目(你的外循环):

        {% for obj in listofobjs %}
            {# do something with obj (just print it for now) #}
            {{ obj }}
        {% endfor %}
        

        然后遍历字典对象中的项目:

        {% for key, value in obj.items %}
            {{ key }}: {{ value }}
        {% endfor %}
        

        【讨论】:

          猜你喜欢
          • 2023-03-14
          • 2012-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-22
          • 1970-01-01
          • 2012-11-23
          相关资源
          最近更新 更多