字典的常见操作1
<1>添加元素
demo:访问不存在的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('id为:%d'%info['id'])
结果:
Traceback (most recent call last):
File "F:/Py projection/practice.py", line 112, in <module>
print('id为:%d' % info['id'])
KeyError: 'id'
如果在使用 变量名[‘键’] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素
添加新的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
# print('id为:%d'%info['id'])#程序会终端运行,因为访问了不存在的键
newId = input('请输入新的学号')
info['id'] = newId
print('添加之后的id为:%d'%info['id'])
结果:
请输入新的学号188
添加之后的id为: 188
<2>删除元素
对字典进行删除操作,有一下几种:
- del
- clear()
del删除指定的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('删除前,%s'%info['name'])
del info['name']
print('删除后,%s'%info['name'])
结果
Traceback (most recent call last):
删除前,班长
File "F:/Py projection/practice.py", line 116, in <module>
print('删除后,%s' % info['name'])
KeyError: 'name'
del删除整个字典
info = {'name':'monitor', 'sex':'f', 'address':'China'}
print('删除前,%s'%info)
del info
print('删除后,%s'%info)
结果
Traceback (most recent call last):
删除前,{'name': 'monitor', 'sex': 'f', 'address': 'China'}
File "F:/Py projection/practice.py", line 116, in <module>
print('删除后,%s' % info)
NameError: name 'info' is not defined
clear清空整个字典
info = {'name':'monitor', 'sex':'f', 'address':'China'}
print('清空前,%s'%info)
info.clear()
print('清空后,%s'%info)
结果
清空前,{'name': 'monitor', 'sex': 'f', 'address': 'China'}
清空后,{}
<3>修改元素
字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
newId = input('请输入新的学号')
info['id'] = int(newId)
print('修改之后的id为%d:'%info['id'])
结果
[外链图片转存失败(img-AdkOPmns-1563528163346)(…/Images/QQ截图20190719094400.jpg)]
<4>根据键访问值
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
print(info['name'])
print(info['address'])
结果:
班长
地球亚洲中国北京
若访问不存在的键,则会报错:
>>> info['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值:
>>> age = info.get('age')
>>> age #'age'键不存在,所以age为None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # 若info中不存在'age'这个键,就返回默认值18
>>> age
18
·dict.get() 访问value
语法格式 dict.get(key[, default])
不确定字典中是否存在某个键而对其进行操作 ,比如获取值 ———>get方法
当key不存在的时候 ,不会抛出异常 ,返回None
遍历
通过for … in …:的语法结构,我们可以遍历字符串、列表、元组、字典等数据结构。
字符串遍历
>>> a_str = "hello itcast"
>>> for char in a_str:
... print(char,end=' ')
...
h e l l o i t c a s t
列表遍历
>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
... print(num,end=' ')
...
1 2 3 4 5
元组遍历
>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
... print(num,end=" ")
1 2 3 4 5
字典遍历
<1> 遍历字典的key(键)
[外链图片转存失败(img-G3VpGSog-1563528163348)(…/Images/Snip20160815_297.png)]
<2> 遍历字典的value(值)
[外链图片转存失败(img-q7ks51HT-1563528163350)(…/Images/Snip20160815_298.png)]
<3> 遍历字典的项(元素)
[外链图片转存失败(img-acTHLseH-1563528163351)(…/Images/Snip20160815_299.png)]
<4> 遍历字典的key-value(键值对)
[外链图片转存失败(img-ss2UG14M-1563528163353)(…/Images/Snip20160815_300.png)]
集合
set()
·无序
·不可重复
·不可更改
内部元素可哈希的
集合本身不可哈希
·用{}括起来的单元素数据集
用途:
·去重