【发布时间】:2011-05-04 13:26:50
【问题描述】:
我在视图层中有一本字典,我将其传递给我的模板。字典值(大部分)是列表,尽管一些标量也存在于字典中。如果存在列表,则将其初始化为 None。
None 值在模板中被打印为“None”,所以我编写了这个小函数来清除 None,然后将列表字典传递给模板。由于我是 Python 新手,我想知道是否有更 Python 的方式来做到这一点?
# Clean the table up and turn Nones into ''
for k, v in table.items():
#debug_str = 'key: %s, value: %s' % (k,v)
#logging.debug(debug_str)
try:
for i, val in enumerate(v):
if val == None: v[i] = ''
except TypeError:
continue;
【问题讨论】:
-
你为什么不用
collections.defaultdict? -
因为我是新手?使用 collections.defaultdict 有什么好处?
标签: python django-templates django-views