美文网首页Python笔记
Python笔记之dict

Python笔记之dict

作者: Sugeei | 来源:发表于2019-02-19 19:33 被阅读0次

    一般而言,官方文档都是最清晰的。
    https://docs.python.org/3.6/library/stdtypes.html

    下面列了一些比较常用的操作, 作为一个工具, 了解它有哪些好用的功能是必要的。
    遇到具体问题的时候就能有针对性的选择。

    删除字典中的元素:

    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    del dict['Name']
    dict
    Out[4]: {'Age': 7, 'Class': 'First'}
    del dict
    dict
    Out[6]: dict
    

    清空字典

    参考http://www.pythontab.com/html/2013/pythonjichu_0507/385.html
    clear()将dick所引用的对象置为空字典,这样当有多个变量引用同一个字典对象时,将影响所有的变量,其值都变为{}

    d1 = {"a":1, "b":2}
    d2 = d1
    d2
    Out[8]: {'a': 1, 'b': 2}
    d1.clear()
    d1
    Out[10]: {}
    d2
    Out[11]: {}
    

    d1={}是将一个空的字典对象赋给d,将只影响被赋值变量,其它引用此字典对象的变量不受影响。

    d1 = {"a":1, "b":2}
    d2=d1
    d1={}
    d2
    Out[15]: {'a': 1, 'b': 2}
    

    get()

    http://www.runoob.com/python/att-dictionary-get.html
    当从字典中取一个可能不存在的key时,get方法很好用。
    例如对d={"a":1, "b":2}这个dict来说,d["e"]将抛出异常。d.get("e")则不会

    d2
    Out[16]: {'a': 1, 'b': 2}
    d2.get("e")
    d2.get("a")
    Out[18]: 1
    d2["e"]
    Traceback (most recent call last):
      File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2882, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-19-3f445af0dbdd>", line 1, in <module>
        d2["e"]
    KeyError: 'e'
    d2.get("e", 0)
    Out[20]: 0
    

    defaultdict

    推荐一篇值得参考的文章:https://www.accelebrate.com/blog/using-defaultdict-python/
    声明defaultdict的时候设置了默认值,当访问一个不存在的key时,defaultdict会自动赋予这个key默认值。
    可以看到访问了不存在的key="e"之后, 最后打印dict中所有key,value时,新增加了"e", Vanilla键值对。

    # coding=utf-8
    from collections import defaultdict
    # https://www.accelebrate.com/blog/using-defaultdict-python/
    # A defaultdict will never raise a KeyError
    ice_cream = defaultdict(lambda: 'Vanilla')
    ice_cream['Sarah'] = 'Chunky Monkey'
    print(ice_cream["e"])
    print(ice_cream["Sarah"])
    for item, value in ice_cream.iteritems():
        print item, value
    

    另一个更朴实的例子

    from collections import defaultdict
    
    newdict = defaultdict(lambda: 0) # 声明此dict中每个key的默认值为0,可以设置为任何自己高兴的值
    # newdict = defaultdict(int) # 这么写也行
    
    for i in range(10):
        newdict["key"] += i
    print newdict
    
    

    相关文章

      网友评论

        本文标题:Python笔记之dict

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