zoukankan      html  css  js  c++  java
  • python学习笔记之--字典

    字典以键值对的形式存在,即一个key对应一个value

    定义:d={}

             d = {key1 : value1, key2 : value2 }

    键必须是唯一的,且为不可变类型(如字符串,数字或元组),可变类型不能作为字典的key

    值可以是任何数据类型


    >>> type(d)
    <class 'dict'>
    >>> isinstance(d,dict)
    True

    #增

    >>> d={}
    >>> d["a"]=1  #字典赋值,字符串作为key
    >>> d
    {'a': 1}
    >>> d[[1]]=2   #列表作为key,报错
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    >>>

    注意:list 不使用 hash 值进行索引,故其对所存储元素没有可哈希的要求;set / dict 使用 hash 值进行索引,也即其要求欲存储的元素有可哈希的要求。Python不支持dict的key为list或dict类型,因为list和dict类型是unhashable(不可哈希)的。

    >>> d[f]=0   #任意字母作为key,报错
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'f' is not defined
    >>> d[(1)]=4   #元祖作为key
    >>> d
    {'a': 1, 1: 4}

    >>> d
    {'a': 1}
    >>> d.keys()
    dict_keys(['a'])
    >>> d.values()
    dict_values([1])

    #改

    >>> d[1]="abc"  #增  key 和value  key为不可变类型
    >>> d
    {1: 'abc'}

    >>> d[1]=66 #key相同时原来的值会被覆盖掉
    >>> d
    {1: 66}
    >>>

    #如果不想被覆盖,可以判断key是否在字典中,然后在操作

     >>> "1" in d

    True

    >>> "1" in d.keys()
    True
    >>>

    >>> d=dict(a=1,b=2)#另一种方式生成字典
    >>> d
    {'a': 1, 'b': 2}
    >>>

     #查:可以按key来查,也可以遍历来查

    #访问字典里的值,把相应的键放入到方括号中

    >>> d={'a':1,'b':2,'c':3}
    >>> d['a']
    1
    >>> d[1]   #字典不是有序的,不能以下标来访问里面的值,否则报错
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    KeyError: 1

    #遍历字典的key的两种方式

    >>> d={'a':1,'b':2}

    >>> for i in d:
    ...     print(i)
    ...
    a
    b


    >>> for i in d.keys():
    ...     print(i)
    ...
    a
    b
    >>>

    #遍历values的方式

    >>> for i in d.values():
    ...     print(i)
    ...
    1
    2
    >>>

    #同时遍历key和values

    >>> for k,v in d.items():
    ...     print(k,":",v)
    ...
    a : 1
    b : 2
    >>>

    #删:能删单一的元素也能清空字典

    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> del d['a']    #删除键‘a’
    >>> d
    {'b': 2, 'c': 3}
    >>> d.clear()   #清空字典
    >>> d
    {}
    >>> del d   #删除字典
    >>> d
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'd' is not defined

    #排序

    >>> user={"user3":"a","user2":"c","user1":"b"}
    >>> user.items()
    dict_items([('user3', 'a'), ('user2', 'c'), ('user1', 'b')])
    >>> sorted(user.items(),key=lambda e:e[0],reverse=False)
    [('user1', 'b'), ('user2', 'c'), ('user3', 'a')]
    >>> a=sorted(user.items(),key=lambda e:e[0],reverse=False)
    >>> a[0]
    ('user1', 'b')
    >>>

    #其他常用内置函数

    >>> d.get("b","100")
    '100'
    >>> d[100]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 100
    >>> d.get("b","100")
    '100'

    >>> zip([1,2,3],[4,5,6])
    <zip object at 0x00000000028C9908>
    >>> list(zip([1,2,3],[4,5,6]))
    [(1, 4), (2, 5), (3, 6)]

    >>> dict(zip([1,2,3],[4,5,6]))
    {1: 4, 2: 5, 3: 6}

    >>> dict([(1,2),(3,4)])
    {1: 2, 3: 4}

    >>> d=d.fromkeys([1,2,3],"a")
    >>> d
    {1: 'a', 2: 'a', 3: 'a'}
    >>> d=d.fromkeys([1,2,3])
    >>> d
    {1: None, 2: None, 3: None}

    >>> d=dict.fromkeys([1,2,3])
    >>> d
    {1: None, 2: None, 3: None}

    >>> d
    {1: None, 2: None}
    >>> d.update({1:100})
    >>> d
    {1: 100, 2: None}
    >>> d.update({100:100})
    >>> d
    {1: 100, 2: None, 100: 100}

    >>> d={1:2,3:4,5:6}
    >>> d.pop(1)
    2
    >>> d.pop(1,100)
    100

    >>> d.popitem()
    (100, 100)
    >>> d.popitem()
    (2, None)
    >>> d.popitem()
    (1, 100)

  • 相关阅读:
    yolo_to_onnx ValueError: need more tan 1 value to unpack
    yolo_to_onnx killed
    C++ 实现二维矩阵的加减乘等运算
    Leetcode 1013. Partition Array Into Three Parts With Equal Sum
    Leetcode 1014. Best Sightseeing Pair
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 219. Contains Duplicate II
    Leetcode 890. Find and Replace Pattern
    Leetcode 965. Univalued Binary Tree
    Leetcode 700. Search in a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/wenm1128/p/11610302.html
Copyright © 2011-2022 走看看