字典集合:一组无序的且不重复的数据(key-value)集合
字典是一个特殊的set集合
1、字典的基本介绍
dic01 = {95001: "张三", 95002: "李四", 95003: "王五"}
# 字典的元素:key,value 比如:95001: "张三"是一个元素
# 冒号前面的称为key,冒号后面的称为value
# 通过key可以访问value,反之不可以
print(dic01[95001])
2、字典的元素不重复
dic01 = {95001: "张三", 95002: "李四", 95003: "王五", 95001: "张三"}
print(dic01)
3、字典的无序
dic01 = {95001: "张三", 95002: "李四", 95003: "王五", 95001: "张三"}
print(dic01[0]) # 报错
执行结果:
C:\python\python.exe C:/python/demo/file3.py
张三
{95001: '张三', 95002: '李四', 95003: '王五'}
Traceback (most recent call last):
File "C:/python/demo/file3.py", line 19, in <module>
print(dic01[0])
KeyError: 0
Process finished with exit code 1
二、什么情况下会用字典
1)比如:学号 + 姓名
list01 = {"张三", "李四"}
dic01 = {95001: "张三", 95002: "李四", 95003: "王五", 95001: "张三"}
2) 比如:姓名 + 成绩
dic02 = {"张三": [23, 98, 56], "李四":[98, 56, 97], "王五":[78, 67, 90]}
print(dic02["李四"])
3)比如:科目 + 成绩
dic03 = {"语文": 95, "数学": 89, "英语": 76}
执行结果:
C:\python\python.exe C:/python/demo/file3.py
[98, 56, 97]
Process finished with exit code 0
三、key-value
1)在字典中,key-value不能重复
2)在字典中,key不能重复,如果一个key对应多个values,最后一个有效
如:
dic01 = {95001: 200, 95002: 345, 95003: 346, 95003: 500}
print(dic01) # 95003的值为500,因为覆盖了前面的346
3)在字典中,value可以重复
如:
dic01 = {95001: 200, 95002: 345, 95003: 346, 95004: 200}
print(dic01)
4)key必须要不可改变的类型:int,str,float,bool,tuple
如:
dic01 = {1.11: "AAA", 2.22: "BBB", 3.33: "CCC", 4.44: "DDD"}
print(dic01)
dic01 = {True: "AAA", False: "BBB"}
print(dic01)
dic01={(11.11, 22.22):"徐家汇", (11.34,33.33):"人民广场", (45.34, 78.12):"东方明珠"}
print(dic01)
5)value可以是任何类型
dic01={(11.11, 22.22):["徐家汇", "人民广场", "东方明珠"],(11.34,33.33):{"AAA", "BBB", "CCC"}, (45.34, 78.12):(111, 222, 333)}
print(dic01)
原文地址:http://blog.51cto.com/13043937/2108848