1.dict表现形式及其特点
1.1.dict表现形式为
dict使用{'key':'value'}形式表示
1.2.dict特点
1、dict中的key值为不可变数据类型,且具有唯一性
2、dict为无序类型
2.增加元素
score = {'chinese':86, 'mathematics':120, 'english':103}
# 添加元素(添加键対值)
score['history'] = 100
print(score) # 输出结果为:{'chinese': 86, 'mathematics': 120, 'english': 103, 'history': 100}
3.删除元素
score = {'chinese':86, 'mathematics':120, 'english':103, 'history': 100}
# 删除键対值
del score['mathematics']
print(score) # 输出结果为:{'chinese': 86, 'english': 103, 'history': 100}
4.修改元素
score = {'chinese':86, 'mathematics':120, 'english':103}
# 修改dict值
score['chinese'] = 150
print(score) # 输出结果为:{'chinese': 150, 'mathematics': 120, 'english': 103}
5.查询定位元素
score = {'chinese': 150, 'english': 103, 'history': 100}
# 查询
print(score['chinese']) # 输出结果:150
6.遍历dict
1.遍历所有的键対值:for key,value in dict.items():
score = {'chinese': 150, 'english': 103, 'history': 100}
# 遍历所有的键対值
for key, value in score.items():
print(key,value)
# 输出结果为:
chinese 150
english 103
history 100
2.遍历dict中的键
score = {'chinese': 150, 'english': 103, 'history': 100}
# 遍历dict中的所有的键
for key in score.keys():
print(key)
3.遍历dict中的值
score = {'chinese': 103, 'english': 103, 'history': 100}
# 遍历dict中的所有的值
for value in score.values():
print(value)
# 结果:
103
103
100
# 去重
for value in set(score.values()):
print(value)
# 结果:
100
103
4.按顺序大小输出结果
score = {'chinese':86, 'mathematics':103, 'english':103}
for value in sorted(set(score.values())):
print(value)
#结果:
86
103