Python -- 字典

字典可以理解为列表的升级版,是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一內建的映射类型

一、字典的创建 

        -字典是另一种可变容器模型,且可存储任意类型对象

        -用{}括起来,元素是键值对的形式,键和值通过:隔开{key:value}

          每个元素之间通过‘,’分隔

                -案例:dic = {'name':'张三','age':18,'height':170}

         -key只能是不可变类型(字符串,数字) 不可以是列表或者字典

         -key是唯一的,不可重复  值可以不唯一

    -如果需要修改‘张三’,则需要先找到他的下边,而字典的下标是根据名字找

        .字典和列表一样可以存取多喝数据

        .列表查询元素通过下标,字典查询元素通过前面的key值

二、字典操作 

--打印字典中的元素

    print(dic['name'])

--修改  通过key找到

[python]  view plain  copy
  1. temp=raw_input("请输入修改后的值")  
  2. dic['name']=temp  
  3. print("修改后的值为%s"%dic['name'])  

--增 如果给字典中不存在的key赋值,则字典中会增加这个元素

[python]  view plain  copy
  1. dic={'name':'淡淡','sex':'男','professional':'计算机科学与技术'}  
  2. vqq=raw_input("请输入QQ号")  
  3. dic['qq']=vqq  
  4. print("添加后的QQ号为%s"%dic['qq'])  

--查

          --len() 查字典中元素个数  一个元素即一个key和一个值

[python]  view plain  copy
  1. dic = {'name':'张三','age':18,'height':170}  
  2. len(dic)  
  3. #3      

            --keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. print 'keys方法:'  
  5. list=d.keys()  
  6. print list  
  7. print u'\niterkeys方法:'  
  8. it=d.iterkeys()  
  9. for x in it:  
  10.     print x  
  11. 运算结果:  
  12. {'three'3'two'2'one'1}  
  13. keys方法:  
  14. ['three''two''one']  
  15.   
  16. iterkeys方法:  
  17. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  18. three  
  19. two  
  20. one  
  21. >>>   
               -- values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={  
  3.     'one':123,  
  4.     'two':2,  
  5.     'three':3,  
  6.     'test':2  
  7.    }  
  8. print d.values()  
  9. 运算结果:  
  10. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  11. [232123]  
  12. >>>   
                 --i tems和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. list=d.items()  
  5. for key,value in list:  
  6.     print key,':',value  
  7. 运算结果:  
  8. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  9. {'three'3'two'2'one'1}  
  10. three : 3  
  11. two : 2  
  12. one : 1  
  13. >>>   
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. it=d.iteritems()  
  5. for k,v in it:  
  6.     print "d[%s]="%k,v  
  7. 运算结果:  
  8. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  9. {'three'3'two'2'one'1}  
  10. d[three]= 3  
  11. d[two]= 2  
  12. d[one]= 1  
  13. >>>   
                 -- has_key函数:检查字典中是否含有给出的键
                    dic.has_key('key')如果可以在字典中,返回Ture,如果不存在返回False
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. print d.has_key('one')  
  5. print d.has_key('four')  
  6. 运算结果:  
  7. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  8. {'three'3'two'2'one'1}  
  9. True  
  10. False  
  11. >>>   
                 -- get函数:访问字典成员    注:get函数可以访问字典中不存在的键,当该键不存在是返回None 
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. print d.get('one')  
  5. print d.get('four')  
  6. 运算结果:  
  7. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  8. {'three'3'two'2'one'1}  
  9. 1  
  10. None  
  11. >>>   
--删除

                -- clear函数:清空整个字典,删除之后可以访问

[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3,'four':4}  
  3. print d  
  4. d.clear()  
  5. print d  
  6. 运算结果:  
  7. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  8. {'four'4'three'3'two'2'one'1}  
  9. {}  
  10. >>>   

                  --del:删除指定元素   删除整个字典(删除之后不能访问)

                  -- pop函数:删除字典中对应的键

[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. d.pop('one')  
  5. print d  
  6. 运算结果:  
  7. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  8. {'three'3'two'2'one'1}  
  9. {'three'3'two'2}  
  10. >>>   
                   -- popitem函数:移出字典中的项
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. d.popitem()  
  5. print d  
  6. 运算结果:  
  7. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  8. {'three'3'two'2'one'1}  
  9. {'two'2'one'1}  
  10. >>>   
--其他

            -- copy函数:返回一个具有相同键值的新字典

[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. x={'one':1,'two':2,'three':3,'test':['a','b','c']}  
  3. print '初始X字典:'  
  4. print x  
  5. print 'X复制到Y:'  
  6. y=x.copy()  
  7. print 'Y字典:'  
  8. print y  
  9. y['three']=33  
  10. print '修改Y中的值,观察输出:'  
  11. print y  
  12. print x  
  13. print '删除Y中的值,观察输出'  
  14. y['test'].remove('c')  
  15. print y  
  16. print x  
  17. 运算结果:  
  18. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  19. 初始X字典:  
  20. {'test': ['a''b''c'], 'three'3'two'2'one'1}  
  21. X复制到Y:  
  22. Y字典:  
  23. {'test': ['a''b''c'], 'one'1'three'3'two'2}  
  24. 修改Y中的值,观察输出:  
  25. {'test': ['a''b''c'], 'one'1'three'33'two'2}  
  26. {'test': ['a''b''c'], 'three'3'two'2'one'1}  
  27. 删除Y中的值,观察输出  
  28. {'test': ['a''b'], 'one'1'three'33'two'2}  
  29. {'test': ['a''b'], 'three'3'two'2'one'1}  
  30. >>>   
注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. from copy import deepcopy  
  3. x={}  
  4. x['test']=['a','b','c','d']  
  5. y=x.copy()  
  6. z=deepcopy(x)  
  7. print '输出:'  
  8. print y  
  9. print z  
  10. print '修改后输出:'  
  11. x['test'].append('e')  
  12. print y  
  13. print z  
  14. 运算输出:  
  15. 输出:  
  16. {'test': ['a''b''c''d']}  
  17. {'test': ['a''b''c''d']}  
  18. 修改后输出:  
  19. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  20. {'test': ['a''b''c''d''e']}  
  21. {'test': ['a''b''c''d']}  
  22. >>>   
                    --fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None  或者指定默认的对应值
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d=dict.fromkeys(['one','two','three'])  
  3. print d  
  4. 运算输出:  
  5. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  6. {'three'None'two'None'one'None}  
  7. >>>    <span style="background-color:rgb(255,255,255);font-family:'-apple-system', 'SF UI Text', Arial, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'WenQuanYi Micro Hei', sans-serif, SimHei, SimSun;color:rgb(79,79,79);font-size:16px;">    </span><span style="background-color:rgb(255,255,255);font-family:'-apple-system', 'SF UI Text', Arial, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'WenQuanYi Micro Hei', sans-serif, SimHei, SimSun;color:rgb(79,79,79);font-size:16px;">    </span>  
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d=dict.fromkeys(['one','two','three'],'unknow')  
  3. print d  
  4. 运算结果:  
  5. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  6. {'three''unknow''two''unknow''one''unknow'}  
  7. >>>           
                 --setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={'one':1,'two':2,'three':3}  
  3. print d  
  4. print d.setdefault('one',1)  
  5. print d.setdefault('four',4)  
  6. print d  
  7. 运算结果:  
  8. {'three'3'two'2'one'1}  
  9. 1  
  10. 4  
  11. {'four'4'three'3'two'2'one'1}  
  12. >>>   
                    --update函数:用一个字典更新另外一个字典
[python]  view plain  copy
  1. # _*_ coding:utf-8 _*_  
  2. d={  
  3.     'one':123,  
  4.     'two':2,  
  5.     'three':3  
  6.    }  
  7. print d  
  8. x={'one':1}  
  9. d.update(x)  
  10. print d  
  11. 运算结果:  
  12. =======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======  
  13. {'three'3'two'2'one'123}  
  14. {'three'3'two'2'one'1}  
  15. >>>   

三、遍历字典中的元素(与for循环遍历列表类似)

3.1遍历字典中所有的key

[python]  view plain  copy
  1. for key in dic.keys():  
  2.     print key  
  3. #qq  
  4. #professional  

3.2遍历字典中所有的value

[python]  view plain  copy
  1. for value in dic.values():  
  2.     print value  
  3. #526879116  
  4. #computerscience  
3.3遍历字典中所有的items
[python]  view plain  copy
  1. for item in dic.items():  
  2.     print item  
  3. #('qq','526879116')  
  4. #('professional','computerscience')  
3.4遍历字典中所有的key-value(键值对)
[python]  view plain  copy
  1. for key,value in dic.items():  
  2.     print('key=%s,value=%s'%(key,value))  
  3. #key=qq,value=526879116  
  4. #key=professional,value=computerscience  

原文链接 :  https://blog.csdn.net/lqian1993/article/details/80226782

猜你喜欢

转载自blog.csdn.net/redpintings/article/details/80238530
今日推荐