字典
字典是将键(key)映射到值(value)的无序数据结构。值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组。
字典:我们查找的单词是key,查找的定义是值。
补充什么是元组?(下一篇具体讲)
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
一、访问字典的值
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
print(dir['1'])
print(dir['5'])
结果:
二、更新字典
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
dir['6']='I hate you'#增加
print(dir)
dir.update({
'1':'aaa'})#修改
print(dir)
dir.update({
'2':'bbb','7':'I like you'})#同时修改和增加也可以
print(dir)
结果:
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
print(dir)
del dir['1']#删掉某个key
print(dir)
结果:
不是所有东西都可以当作Key
dir={
'1':'A','2':'B','3':'C','4':'D','5':'I love you'}
dir[['aaaaa']]
print(dir)
错误:
三、使用get()方法返回给定键的值
这样写的话,因为没有run这个key,所以会报错
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount['run'])
结果报错:
但是如果这样写:
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount.get('run',0))#这个0是你自己定义的如果不存在范围的默认的值
print(storyCount.get('run'))#如果你没有设置的话,默认是none
结果:
四、删除键,但同时可以返回值
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
count=storyCount.pop('is')
print(count)
print(storyCount)
结果:
五、遍历字典
storyCount = {
'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
print(storyCount.keys())#所有key
print(storyCount.values())#所有value
print('-------------------------')
for key in storyCount:
print(key)
print("-------------------------")
for value in storyCount.items():#注意我试了一下这里没有items()不行
print(value)
print("-------------------------")
for key,value in storyCount.items():#注意我试了一下这里没有items()不行
print(key,value)
结果: