如何通过Python defaultdict迭代?

时间:2014-05-01 10:56:35

标签: python

我有一本看起来像这样的字典。

defaultdict(<type 'list'>,
{
 2012: [Counter({1: 1, 2: 1, 4: 1}), 3],
 2013: [Counter({4: 2, 12: 1, 5: 1, 6: 1}), 5],
 2014: [Counter({4: 3, 1: 1, 2: 1, 3: 1}), 6]}
)

我正试图通过Counter dict迭代。像这样。

2012
1 1
2 1
1 4
3

2013
4 2
12 1
5 1
6 1
5

这是我试过的代码。

for key, value in d.iteritems():
    for k, v in value:
        print k, v

这是错误:

Traceback (most recent call last):
  File "C:/test.py", line 42, in <module>
    for k, v in value:
ValueError: too many values to unpack

JINJA2解决方案:

{% extends "base.html" %}
{% block title %}Archive{% endblock %}
{% block content %}

<dl>
{% for key, value in d.iteritems() %}
    <dt><a href="/{{ key }}">{{ key }}</a> ({{ value[1] }})</dt>
    {% for m, c in value[0].items() %}
       <dd><a href="/{{ key }}/{{ m }}">{{m|month_number}}</a> ({{ c }})</a></dd>
        {{ a }}
    {% endfor %}
{% endfor %}
</dl>

{%endblock%}

2 个答案:

答案 0 :(得分:6)

>>> for year, (counter, other_thing) in d.items():
...     print(year)
...     for k, v in counter.items():
...         print(k, v)
...     print(other_thing)
...     print()
...     
2012
1 1
2 1
4 1
3

2013
4 2
12 1
5 1
6 1
5

2014
1 1
2 1
3 1
4 3
6

答案 1 :(得分:3)

接受您的数据结构化,明确迭代:

for k, v in d.items():
    print(k)
    c, x = v
    for kk, vv in c.items():
        print(kk, vv)
    print(x)