SRFBN

转载自:https://blog.csdn.net/NCU_wander/article/details/105529494

 

1、**

list变量前面加星号,字典变量前面加两个星号;是将其作为参量进行传递,传递进去之后仍然保持其原字典或者list的原性质;最为常见的就是argparse模块中的参数分解。

复制代码
extra= {'city':'beijing','job':'engineer'}
def f(**kw):
    kw['city'] = 'shanghai'
    for k,w in kw.items():
        print(type(k),k,w)

        if w in ['shanghai']:
            print('本次循环到了city这一环节')



f(**extra)
print(extra)
<class 'str'> city shanghai
本次循环到了city这一环节
<class 'str'> job engineer
{'city': 'beijing', 'job': 'engineer'}
复制代码

 

2、dict中的__missing__用法

复制代码
class NoneDict(dict):
    def __missing__(self, key):
        return None
# convert to NoneDict, which return None for missing key.
def dict_to_nonedict(opt):
    if isinstance(opt, dict):
        new_opt = dict()
        for key, sub_opt in opt.items():
            new_opt[key] = dict_to_nonedict(sub_opt)
        return NoneDict(**new_opt)
        #return new_opt
    elif isinstance(opt, list):
        return [dict_to_nonedict(sub_opt) for sub_opt in opt]
    else:
        return opt

opt = [1,2,3,4]
print(dict_to_nonedict(opt))
[1, 2, 3, 4]
opt = {'a':12, 'b':116, 'c':{'d':5, 'e':66}}
print(opt['f'])
Traceback (most recent call last):
  File "a.py", line 38, in <module>
    print(opt['f'])
KeyError: 'f'
print(dict_to_nonedict(opt))

print(dict_to_nonedict(opt)['f'])

{'a': 12, 'b': 116, 'c': {'d': 5, 'e': 66}}
None
复制代码

最终的输出结果为,可以看到在最后一行直接打印一个不存在的key时,仍然可以做到返回None值而非报错

如果不是return NoneDict而是直接return new_opt,则在在最后一行打印时会直接报错。

 

posted on   cltt  阅读(281)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2019-09-18 PAt 1099
2019-09-18 多项式求和
2019-09-18 pat 1100
2019-09-18 getline 函数
2018-09-18 zoj 4057
2018-09-18 zoj 4056
2018-09-18 zoj 4054
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示