6
Python__14--字典的常用操作
source link: https://blog.51cto.com/husheng/5969384
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python__14--字典的常用操作
精选 原创Table of Contents
1 字典的常用操作
1.1 key的判断 in、not in
scores={'张三':100,'李四':98,'王五':90}
print('张三' in scores)
print('张三' not in scores)
1.2 删除指定键值对 del
del scores['张三']
print(scores)
#输出为={'李四':98,'王五':90}
1.3 清空字典元素 scores.clear()
输出为{}
1.4 字典元素的新增
scores['陈六']=66
#输出为scores={'张三':100,'李四':98,'王五':90,'陈六':66}
1.5 字典元素的修改
scores['张三']=88
1.6 获取字典视图
-
scores.keys()
scores={'张三':100,'李四':98,'王五':90} keys=scores.keys() print(keys) #输出为dick.keys(['张三','李四','王五']) print(list(keys)) #输出为['张三','李四','王五']
-
scores.values()
-
scores.items()
scores={'张三':100,'李四':98,'王五':90} keys=scores.items() rint(items) #输出为dick.items([('张三',100),('李四',98),('王五',90)]) print(list(items)) #输出为[('张三',100),('李四',98),('王五',90)]
1.7 字典元素的遍历
测试代码:
scores={'张三':100,'李四':98,'王五':90}
for item in scores:
print(item,scores[item],scores.get(item))
测试结果:
1.8 测试
测试代码:
scores={'张三':100,'李四':98,'王五':90}
print(scores,id(scores))
print('张三' in scores)
print('张三' not in scores)
del scores['张三']
print(scores,id(scores))
scores.clear()
print(scores,id(scores))
scores['陈六']=66
print(scores,id(scores))
scores['张三']=88
print(scores,id(scores))
keys=scores.keys()
print(keys)
测试结果:
- 赞
- 收藏
- 评论
- 分享
- 举报
上一篇:Python__13--字典
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK