字典是另一种可变容器模型,且可存储任意类型对象。字典包含键(左侧)和值(右侧)两部分,每个键和值之间用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 。字典中的元素没有索引编号,也不能进行切片,根据键去找值,比如要引用 services 字典中第一个元素的值,使用 services['ftp']。
>>> services = {'ftp':21,'ssh':22,'http':80} #ftp为键,21为值
>>> services['ssh']
22
>>> services['http']
80
>>> services['http'] = 8080 #键是不能修改的,可以修改值
>>> services
{'ftp': 21, 'ssh': 22, 'http': 8080}
>>> services['https'] = 443 #增加新的元素,https之前不存在
>>> services
{'ftp': 21, 'ssh': 22, 'http': 8080, 'https': 443}
>>> services['http'] = 80 #http已经存在,则进行修改
>>> services
{'ftp': 21, 'ssh': 22, 'http': 80, 'https': 443}
>>> services.keys()
dict_keys(['ftp', 'ssh', 'http', 'https'])
>>> services.values()
dict_values([21, 22, 80, 443])
>>> services.items()
dict_items([('ftp', 21), ('ssh', 22), ('http', 80), ('https', 443)])
>>> 'http' in services #查看是否存在'http'键
True
>>> 80 in services #查看是否存在 80 的值,是查不到值的
False
>>> 80 in services.values() #配合values()方法进行查看即可
True
>>> for i in services:
... print(i)
...
ftp
ssh
http
https
>>> for i in services: #i取值为键
... print(services[i]) #services[i]即可转换为字典中每个元素的值
...
21
22
80
443
>>> for i in services.values(): #i取值直接为值
... print(i)
...
21
22
80
443
>>> for i in services: #取值为键
... print(f'{i}:{services[i]}') #字符串格式化,f' {i}'即为键 :{services[i]即为键的值}'
...
ftp:21
ssh:22
http:80
https:443
方法二
>>> for m,n in services.items(): #定义两个循环变量在services.items()进行取值
... print(f'{m}:{n}') #字符串格式化输出如下
...
ftp:21
ssh:22
http:80
https:443