def semiflatten(multi):
"""Convert a MutiDict into a regular dict. If there are more than one value
for a key, the result will have a list of values for the key. Otherwise it
will have the plain value."""
if multi:
result = multi.to_dict(flat=False)
for k, v in result.items():
if len(v) == 1:
result[k] = v[0]
return result
else:
return multi
在学习这个函数并测试的时候发现一个问题:
MutiDict是什么?我在httpbin的所有源码中搜索了这个关键字,没有其他任何地方再次涉及
MutiDict,无奈,找不到理论知识就没办法完整的理解这部分代码,就在werkzeug的官网上找
到了MutiDict的理论解释,摘录如下:
http://werkzeug.pocoo.org/docs/0.12/datastructures/
根据链接中的解释以及示例,我构造了如下测试代码:
from werkzeug.datastructures import MultiDict def semiflatten(multi): """Convert a MutiDict into a regular dict. If there are more than one value for a key, the result will have a list of values for the key. Otherwise it will have the plain value.""" if multi: result = multi.to_dict(flat=False) for k, v in result.items(): if len(v) == 1: result[k] = v[0] return result else: return multi sample = MultiDict([('a', 'b'), ('a', 'c')]) print sample semi = semiflatten(sample) print semi
代码的输出结果如下:
MultiDict([('a', 'b'), ('a', 'c')])
{'a': ['b', 'c']}
结论如下:
这个函数中真正重要的是.to_dict(flat=False)
它的作用就是{'a': ['b', 'c']},即将一个key对应多个value的情况转换为,一个key对应一个value,而转换后的value是一个包含所有value的list
if len(v) == 1: result[k] = v[0]这两条语句的作用我不明白,我认为是完全没有必要的,当然,也可能是作者有自己的设计想法,只是我现在还没有察觉出;