python - 如何遍历 Python defaultdict?

标签 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]}
)

我正在尝试迭代 through Counter 指令。像这样。

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>

{% 端 block %}

最佳答案

>>> 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

关于python - 如何遍历 Python defaultdict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23406305/

相关文章:

python - 使用 object.__setattr__ 时出现 AttributeError

python - 不使用 `show()` 的 Matplotlib 事件处理

python - 错误 13 权限被拒绝 : 'file.mp3' Python

python - 如何在 python 中用相等的非重叠正方形近似覆盖一个(不一定是凸的)多边形?

Python:从文本文件中读取混合数据

python - 将UTC时间字符串转换为日期时间对象

python - 来自 Matplotlib 的 Pane 边缘可见性的 3D 图形

python - web.py 获取请求头

python - 如何在 Azure Databricks 笔记本中调试长时间运行的 python 命令?

python - 如果 Pandas 有公共(public)键,它们会将行中的某些值转换为列