编程语言
首页 > 编程语言> > Python基础(字典)

Python基础(字典)

作者:互联网

Python基础(字典)

什么是字典

scores={'张三':100,'李四':98,'王五':45}

字典名:scores

‘张三’ 键 ; 100 值

第一个放进字典的键不一定是放在第一个位置,位置是通过hash值来决定的

理解什么是不可变序列和可变序列

举例子:不可变序列:整数 和字符串

可变序列:目前学的:列表和字典

字典的实现原理

字典的创建

字典的常见操作

字典元素的获取

print('-----------获取字典的元素----------')
scores={'张三':100,'李四':98,'王五':45}
'''第一种方式,使用[]'''
print(scores['张三'])
print(scores['陈六'])

输出:

-----------获取字典的元素----------
100
    print(scores['陈六'])
KeyError: '陈六'

第二种:

'''第二种方式'''
print(scores.get('张三'))
print(scores.get('陈六')) #None 这种不会报错
print(scores.get('麻七',99))  #99是获取不到时的替代品

输出:

100
None
99

字典元素的增删改查

key的判断

​ key的判断:

print('-----key的判断----')
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)
print('张三' not in scores)

输出:

-----key的判断----
True
False

字典元素的删除

del scores['张三'] #删除指定的key-value 对
print(scores)

输出:

{'李四': 98, '王五': 45}

张三没了

字典的晴空

scores.clear()

print('-----字典的清空----')
print(scores)
scores.clear()
print(scores)

输出:

-----字典的清空----
{'李四': 98, '王五': 45, '陈六': 112}
{}

字典元素的新增

print(scores)
scores['陈六'] = 115
print(scores)

输出:

{'李四': 98, '王五': 45}
{'李四': 98, '王五': 45, '陈六': 115}

字典元素的修改

scores[‘陈六’]=112

print('----修改元素----')
print(scores)
scores['陈六']=112
print(scores)

输出:

----修改元素----
{'李四': 98, '王五': 45, '陈六': 115}
{'李四': 98, '王五': 45, '陈六': 112}

获取字典视图的三个方法

获取字典视图

字典元素的遍历

for item in scores:

​ print(item)

print('----字典元素的遍历----')
scores={'张三':100,'李四':99,'王五':88}
for item in scores:
    print(item,scores[item],scores.get(item))

输出:

----字典元素的遍历----
张三 100 100
李四 99 99
王五 88 88

字典的特点

字典的生成式

内置函数zip()

标签:Python,基础,----,李四,scores,print,100,字典
来源: https://blog.csdn.net/qq_36068496/article/details/123167515