美文网首页
Python解析dict.update()方法

Python解析dict.update()方法

作者: 时间煮菜 | 来源:发表于2020-02-28 11:04 被阅读0次
    • 在构建MySQL健康检查器的时候,遇到以下dict.update语法:
    def sync_error(action_name, error, **kwargs):
        resp_dict = {}
    
        resp_dict['action'] = action_name
        resp_dict['is_success'] = False
        error = str(error) if isinstance(error, Exception) else error
        resp_dict['error'] = error
    
        if kwargs:
            resp_dict.update(kwargs)
    
        return resp_dict
    
    • 经过查阅对于dict objectupdate函数的理解如下:
    • 使用方法如下:
    dict.update(dict2)
    
    • dict2 -- 添加到指定字典dict里的字典。
    • 举个栗子🌰:
    In [82]: dic = {"A":"a", "B":"b"}
    # print 出初始的 dict 对象, 输出结果为 {"A":"a", "B":"b"}  
    In [83]: print dic
    {'A': 'a', 'B': 'b'}
    # 如果update的键值在字典中已经存在的话,更新该对应的键值 
    In [84]: dic.update(A="Aa")
    # 输出 {'A': 'Aa', 'B': 'b'}  
    In [85]: print dic
    {'A': 'Aa', 'B': 'b'}
    # 如果添加的键值不存在,加入键值对到字典中
    In [86]: dic.update(C="C")
    # 输出 {'A': 'Aa', 'C': 'C', 'B': 'b'}  
    In [87]: print dic
    {'A': 'Aa', 'C': 'C', 'B': 'b'}     
    

    相关文章

      网友评论

          本文标题:Python解析dict.update()方法

          本文链接:https://www.haomeiwen.com/subject/tvukhhtx.html