繁体   English   中英

为什么dict.get('',None)在Python中返回一个列表?

[英]why could dict.get('',None) return a list in Python?

我正在阅读一个源代码,并对此有所怀疑。这里的'config'是一个字典。

        server_port = config.get('server_port', None)

为什么config.get('server_port',None)返回一个列表?

    if server_port:
        if type(server_port) == list:
            for a_server_port in server_port:
                config['port_password'][a_server_port] = config['password']
        else:
            config['port_password'][str(server_port)] = config['password']

因为“ server_port”是存储在字典中的列表的键。

如果不存在键值对,则“无”仅指定默认值。

如果你有字典

thing = {
    "name": "Bob,
    "height": 19,
}

您可以使用thing.get()请求键的值

>>> thing.get("name")
Bob

dict.get()有一个可选参数default=None ,如果在字典键中找不到该键,则返回该参数。

>>> thing.get("someUnknownKey")
None 

>>> thing.get("someUnknownKey", default="If key is not found, print this")
If key is not found, print this

因此server_port是字典中的可能键,如果找不到,则返回None 如果找到,则返回键server_portvalue -预期为list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM