学习httpbin源码记录(四)

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]

这两条语句的作用我不明白,我认为是完全没有必要的,当然,也可能是作者有自己的设计想法,只是我现在还没有察觉出;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值