#11 Python字典

前言

前两节介绍了Python列表和字符串的相关用法,这两种数据类型都是有序的数据类型,所以它们可以通过索引来访问内部元素。本文将记录一种无序的数据类型——字典!

一、字典与列表和字符串的区别

  • 字典是无序的,列表和字符串是有序的

  • 字典使用 key-value(键-值对)存储,列表和字符串为单元素存储

  • 字典的key值唯一,列表和字符串元素可以相同

  • 字典的访问速度远高于列表和字符串的访问速度

  • 字典通常被用作存储,列表和字符串常用来工作

二、字典的用法

在介绍其详细用法之前,先来看看其包含的方法:

In [1]: dir(dict)
Out[1]:
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

从上面可以看到,字典的方法屈指可数,麻雀虽小,五脏俱全啊

1.字典的初始化

通过前文可知,字典是被一对花阔号括起来,内部元素采用 key-value 形式存储的数据类型:

普通初始化:

In [5]: systems = {'windows':10,'linux':'centos 6'}      # 初始化一个字典,含有不同的数据类型

In [6]: systems = {'windows':10,'windows':8}             # 字典的 key 值必须唯一,虽然重复时不报错,但访问时有问题

In [7]: systems['windows']                               # 访问Windows时,随机给出一个值,这是不希望的,所以在创建字典时严格控制 key 的唯一
Out[7]: 8

In [9]: systems = {'windows':10,'linux':{'centos': 6}}   # 字典可以嵌套

高级初始化:dict.setdefault()

In [24]: systems     # 之前存在的字典
Out[24]: {'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

In [27]: systems.setdefault('ios',12)             # 使用dict.setdefault()方法传入新的 key-value:'ios':12
Out[27]: 12

In [28]: systems
Out[28]: {'ios': 12, 'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

In [29]: systems.setdefault('linux','centos 7')   # setdefault方法对于字典里没有的key是新建,对于已经存在的key来说,则不会改变原有的值,并且返回原有的值
Out[29]: 'centos 6'
  
In [30]: systems    # 可以看到已经存在的 'linux'的值并没有被改变
Out[30]: {'ios': 12, 'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

# 这种方法极为适合于未知的字典

通过列表初始化:dict.formkeys()

In [59]: systems={}   # 创建一个空字典

In [61]: systems.fromkeys(['linux','windows','ios'],['centos 6',10,12])
Out[61]:
{'ios': ['centos 6', 10, 12],
 'linux': ['centos 6', 10, 12],
 'windows': ['centos 6', 10, 12]}

# 可以看到,这种方法超级坑,并不是想象中的一一对应,而是一对多

2.字典的访问

通过字典名加一对方括号 dict[key] 来访问字典的元素:

In [11]: systems = {'windows':10,'linux':'centos 6'}

In [12]: systems['windows']
Out[12]: 10

In [13]: systems['linux']
Out[13]: 'centos 6'

循环访问:字典本身是可以循环的:

In [14]: systems
Out[14]: {'linux': 'centos 6', 'windows': 10}

In [15]: for key in systems:          # 可以看到字典默认循环 key
    ...:     print(key)
    ...:
linux
windows

In [16]: for key in systems:          # 可以通过方括号的访问方式来得到value值
    ...:     value = systems[key]
    ...:     print(key,value)
    ...:
linux centos 6
windows 10

更高级的循环访问:使用 dict.items()

In [17]: for key,value in systems.items():   # 使用字典方法items()来循环遍历字典,但是会把字典转换为列表,还是少用哇
    ...:     print(key,value) 
    ...:
linux centos 6
windows 10

3.字典的增加和修改

字典的增加:dict[新的key] = 新的value

In [19]: systems
Out[19]: {'linux': 'centos 6', 'windows': 10}

In [20]: systems['ubuntu'] = 16     # 直接增加即可

In [21]: systems
Out[21]: {'linux': 'centos 6', 'ubuntu': 16, 'windows': 10}

# 通过上面代码明显发现字典是无序的

字典的修改:dict[存在的key] = 新的value

In [21]: systems
Out[21]: {'linux': 'centos 6', 'ubuntu': 16, 'windows': 10}

In [22]: systems['ubuntu'] = 17     # 直接改就行

In [23]: systems
Out[23]: {'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

字典的更新:dict1.updata(dict2)

In [31]: systems1 = {'ios':12,'windows':8}

In [34]: systems2 = {'linux':'centos 6','windows':10}

In [35]: systems1.update(systems2)      # 使用systems2更新systems1

In [36]: systems1
Out[36]: {'ios': 12, 'linux': 'centos 6', 'windows': 10}

4.字典的删除

删除指定键值对方法1:dict.pop(key)

In [37]: systems
Out[37]: {'ios': 12, 'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

In [38]: systems.pop('ios')    # 删除'ios',并且返回其值
Out[38]: 12

In [39]: systems
Out[39]: {'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

删除指定键值对方法2:使用del

In [39]: systems
Out[39]: {'linux': 'centos 6', 'ubuntu': 17, 'windows': 10}

In [40]: del systems['linux']

In [41]: systems
Out[41]: {'ubuntu': 17, 'windows': 10}

随机删除键值对:dict.popitem()

In [41]: systems
Out[41]: {'ubuntu': 17, 'windows': 10}

In [42]: systems.popitem()   # 随机删除键值对,并返回此键值对
Out[42]: ('windows', 10)

In [43]: systems
Out[43]: {'ubuntu': 17}

清空字典元素:dict.clear()

In [64]: systems = {'linux':'centos 6','windows':10}

In [65]: systems.clear()

In [66]: systems    # 字典仍然存在,只是变成了一个空字典
Out[66]: {}

5.字典的查找

使用关键字 in :

In [46]: systems = {'linux':'centos 6','windows':10}

In [47]: 'linux' in systems
Out[47]: True

In [48]: 'iso' in systems
Out[48]: False

使用访问查找:

In [49]: systems
Out[49]: {'linux': 'centos 6', 'windows': 10}

In [50]: systems['linux']    # 访问键值对,有返回值证明存在
Out[50]: 'centos 6'
 
In [51]: systmes['ios']      # 抛出异常,证明没有此元素
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-51-e5e3f5004036> in <module>
----> 1 systmes['ios']

KeyError: 'ios'

使用 dict.get(key) 查找:

In [52]: systems
Out[52]: {'linux': 'centos 6', 'windows': 10}

In [53]: systems.get('linux')    # 查找'linux',有返回值,证明存在
Out[53]: 'centos 6'

In [54]: systems.get('ios')      # 没有返回值,证明不存在

# 和访问的区别就在于没有此元素时,get方法不会报错

6.字典的统计

统计key:dict.keys()

In [55]: systems
Out[55]: {'linux': 'centos 6', 'windows': 10}

In [56]: systems.keys()
Out[56]: dict_keys(['linux', 'windows'])

统计value:dict.values()

In [57]: systems
Out[57]: {'linux': 'centos 6', 'windows': 10}

In [58]: systems.values()
Out[58]: dict_values(['centos 6', 10])

7.字典的拷贝

请参考列表的拷贝,大同小异ㄟ( ▔, ▔ )ㄏ

posted @ 2019-01-29 11:39  MinuteSheep  阅读(322)  评论(0编辑  收藏  举报