有没有更Pythonic的方法来进行这个字典迭代?
我在视图层中有一本字典,我将其传递给我的模板。字典值(大部分)是列表,尽管字典中也存在一些标量。如果存在列表,则将其初始化为 None。
None 值在模板中被打印为“None”,因此我编写了这个小函数来在将列表字典传递给模板之前清除 None。由于我是Python新手,我想知道是否可以有一种更Pythonic的方法来做到这一点?
# 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;
I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None.
The None values are being printed as 'None' in the template, so I wrote this little function to clean out the Nones before passing the dictionary of lists to the template. Since I am new to Python, I am wondering if there could be a more pythonic way of doing this?
# 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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您看过集合中的
defaultdict
吗?您将有一个形成的字典,当查询某个键并且该键不存在时,它会初始化一个空列表。
Have you looked at
defaultdict
within collections? You'd have a dictionary formed viawhich initializes an empty list when a key is queried and that key does not exist.
或者在 Python 2.7+ 中,使用字典理解语法:
or in Python 2.7+, use the dictionary comprehension syntax: