Python中文
首页
教程
问答
标签
搜索
登录
注册
如何遍历Python defaultdict?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我有一本这样的字典。</p> <pre><code>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]} ) </code></pre> <p>我正试着用这种方法来迭代遍历计数器指令。</p> <pre><code>2012 1 1 2 1 1 4 3 2013 4 2 12 1 5 1 6 1 5 </code></pre> <p>这是我试过的密码。</p> <pre><code>for key, value in d.iteritems(): for k, v in value: print k, v </code></pre> <p>错误如下:</p> <pre><code>Traceback (most recent call last): File "C:/test.py", line 42, in <module> for k, v in value: ValueError: too many values to unpack </code></pre> <p><strong>JINJA2解决方案:</strong></p> <pre><code>{% 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> </code></pre> <p>{%endblock%}</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>接受您的数据是结构化的,按如下方式显式迭代:</p> <pre><code>for k, v in d.items(): print(k) c, x = v for kk, vv in c.items(): print(kk, vv) print(x) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
VirtualEnvRapper错误:路径python2(来自python=python2)不存在
1 回答
virtualenvs上的pyinstaller,没有名为导入错误的模块
6 回答
virtualenvs是否可以退回到用户包而不是系统包?
5 回答
virtualenvwrapper CentOS7
2 回答
virtualenvwrapper IOError:[Errno 13]权限被拒绝
4 回答
virtualenvwrapper mkproject和shell在windows中的启动问题?
1 回答
virtualenvwrapper mkvirtualenv不工作但没有错误
9 回答
Virtualenvwrapper python bash
10 回答
virtualenvwrapper:“workon”何时更改到项目目录?
6 回答
virtualenvwrapper:mkvirtualenv可以工作,但是rmvirtualenv返回bash:没有这样的文件或目录
7 回答
virtualenvwrapper:virtualenv信息存储在哪里?
5 回答
virtualenvwrapper:命令“python设置.pyegg_info“失败,错误代码为1
6 回答
virtualenvwrapper:如何将mkvirtualenv的默认Python版本/路径更改为ins
10 回答
Virtualenvwrapper:模块“pkg_resources”没有属性“iter_entry_points”
10 回答
Virtualenvwrapper:没有名为virtualenvwrapp的模块
2 回答
Virtualenvwrapper.bash_profi的正确设置
10 回答
Virtualenvwrapper.hook:权限被拒绝
5 回答
virtualenvwrapper.sh:fork:资源暂时不可用Python/Djang
10 回答
Virtualenvwrapper.shlssitepackages命令不工作
2 回答
Virtualenvwrapper.sh函数在bash sh中不可用
10 回答