一 字典dict特性
字典dict是一种key - value 与Java的中Map有点类似
-
dict是无序的
-
key必须是唯一的 且必须是可hash 不可变类型 如int str tuple frozenset
-
>>> hash(1) 1 >>> hash('a') 6134580092184725428 >>> tu = (1,2,) >>> hash(tu) 3713081631934410656 >>> hash(frozenset(st)) -1826646154956904602 >>> li = [1,2,3] >>> dic = { 'a':1} >>> st = { 1,2} >>> hash(li) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> hash(dic) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> hash(st) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set'
-
-
查询速度快,比列表快多了
-
比list占用内存多
-
字典是可修改的
二 定义一个字典
字典中的key值, 必须是可hash类型. 即类型为不可变类型. 如: str/number/元祖/字典/frozenset
d1 = {
} # 构造一个空字典
d2 = {
'spam': 2, 'eggs': 3} # 构造2个key-value的元素的字典
d3 = {
'food': {
'eggs'