python 字典( BIF内置方法 )

字典是python唯一的映射类型------(key,value),即由多个key和对应的value组成

原始的,通过brand查找到logon

def index1():
    brand = ['123','345','567','789']
    logon = ['哈1','哈2','哈3','哈4']
  print("567的logon:",logon[brand.index('567')])

创建字典,使用dict这个工厂函数来创建

 dic1 = {123: '哈1', '345': '哈12', '567': '哈123', '789': '哈1234'}
 dict2={} #创建空的字典
 dict3 =dict((('1',12), ('2',123), ('3',1234), ('4',12345)))
 dict4 = dict({123:'hhhh','345':'飞舞','567':'够细','789':'asdff' })
 dict5 = dict(aaaaa='111', bbbbb='2222')
dict5['aaaaa'] = '修改了,,,,,'   #修改字典
print(dict5)  #{'bbbbb': '2222', 'aaaaa': '修改了,,,,,'}
dict5['ccccc'] = '33333'  #新增字典
print(dict5)  #{'bbbbb': '2222', 'aaaaa': '修改了,,,,,', 'ccccc': '33333'}

通过key值访问:dict5['aaaaa']   #修改了,,,,,


访问字典  keys()、values()、items()

def fun1():
    dect1 = {}
    print(dect1.fromkeys((1,2,3),'haha'))
    #{1: 'haha', 2: 'haha', 3: 'haha'}

    dect1 = dect1.fromkeys(range(5),'赞')
    print(dect1)
    #{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}

    for item in dect1.items():
        print(item)
        # (0, '赞')
        # (1, '赞')
        # (2, '赞')
        # (3, '赞')
        # (4, '赞')


    for each in dect1.keys():
        print(each)


    for value in dect1.values():
         print(value)

当获取的key不在列表中时,可以给一个默认值表示:

如列表中没有key为10的数据

 print(dect1.get(10))     #None
 print(dect1.get(10),'没有....')      #没有....


成员资格运算符:in、not  in

Python 有一个用于检查一个值是否在序列 / 列表 / 字符串 / ...中,如果在序列中返回 True,否则返回 False,叫成员资格运算符

如:

4  in dict5    #True(dict5字典中存在key为4的数据)
31 in dict5    #False(不存在)
字典中:查找的是key ,不是value
序列中:查找的是value,不是key 


清空字典: clear()

dect1.clear()

不建议使用 dect1={}方法来清空,举例子如下:

    dect2 = dect1
    dect1 = {}
    print(dect1)        #{}
    print(dect2)        #{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
这里dect1 、dect2指向同一个字典地址,是独立的两个个体,清空了dect1,dect2还存在

字典拷贝:copy()

copy()只拷贝表层数据,不指向原数据的地址
def fun2():
    a = {1: 'one', 2: 'two', 3: 'three'}
    b = a
    c = a.copy()
    print(id(a))        #10255176
    print(id(b))        #10255176
    print(id(c))        #10255624
    b[4] = 'four'
    print(a)            #{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
    print(b)            #{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
    print(c)            #{1: 'one', 2: 'two', 3: 'three'}

字典数据删除:pop(),popitem()

pop(): 删除指定key的数据

popitem():随机删除一个数据(原本是删除最后一个数据,但因字典数据没有一定的顺序,所以随机)

def fun3():
    a = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
    print(a.pop(2))         #删除key为2的数据:two
    print(a)                # {1: 'one', 3: 'three', 4: 'four'}  
    print(a.popitem())      #  随机弹出一个数据:(1, 'one')
    print(a)                # {3: 'three', 4: 'four'}

向字典中插入数据: setdefault()

a.setdefault(5,'five')          #{3: 'three', 4: 'four', 5: 'five'}
b = {'小白':'dog'}
a.update(b)          #{'小白': 'dog', 3: 'three', 4: 'four', 5: 'five'}    






猜你喜欢

转载自blog.csdn.net/register_2/article/details/80252748