转载自: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,则在在最后一行打印时会直接报错。