Is there a more pythonic way to do this dictionary iteration?
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开发者_如何学JAVA 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;
Have you looked at defaultdict
within collections? You'd have a dictionary formed via
defaultdict(list)
which initializes an empty list when a key is queried and that key does not exist.
filtered_dict = dict((k, v) for k, v in table.items() if v is not None)
or in Python 2.7+, use the dictionary comprehension syntax:
filtered_dict = {k: v for k, v in table.items() if v is not None}
精彩评论