Dictionary是一種無序性(unordered)的key-value pair。
以下分別就key和value來自問自答
key是否能重複呢?
在python官方的說明文件中提到key有唯一性
an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)
key可以是什麼呢?
因為需要當作取得value的索引,若key會被外部因素變來變去,造成上一秒指定的key下一秒就被改掉,似乎也不太合理,所以必須為immutable type
。舉例來說: strings, numbers, tuple or Enumeration members都可以。
嚴格上來看,若要使用tuple作為key,則tuple內的元素也必須要immutable。
# dict key : Uniqueness, immutable type
demo = { 'height': 170, 'weight': 58, 'height': 20 }
print( "demo data:{}".format(demo) )
# demo data:{'height': 20, 'weight': 58}
demo2 = { 'height': 170, 'weight': 58, 'Height': 20 }
print( "demo2 data:{}".format(demo2) )
# demo2 data:{'height': 170, 'weight': 58, 'Height': 20}
demo3 = { 5: '170', 6: '58' }
print( "demo3 data:{}".format(demo3) )
# demo3 data:{5: '170', 6: '58'}
demo4 = {}
list_as_key = [0, 1, 2 ,3 ,4]
tuple_as_key = ('0', 1, '2' ,3 ,4)
tuple_as_key_with_list = (0, 1, 2 ,3 ,4, list_as_key)
try:
demo4[list_as_key] = 5
print( "Type Error: {0}".format(e) )
except TypeError as e:
print( "Type Error: {0}".format(e) )
try:
demo4[tuple_as_key] = 5
print( "demo4 data:{}".format(demo4) )
except TypeError as e:
print( "Type Error: {0}".format(e) )
try:
demo4[tuple_as_key_with_list] = 5
print( "demo4 data:{}".format(demo4) )
except TypeError as e:
print( "Type Error: {0}".format(e) )
# Type Error: unhashable type: 'list'
# demo4 data:{('0', 1, '2', 3, 4): 5}
# Type Error: unhashable type: 'list'
value可以是什麼呢?
理論上甚麼都可以
和list相同,dictionary也是mutable
# dict is mutable
demo = { 'height': 170, 'weight': 58, 'age': 20 }
print( "demo data:{}".format(demo) )
print( "id of demo data:{}".format(id(demo)) )
# demo data:{'height': 170, 'weight': 58, 'age': 20}
# id of demo data:139675823957480
demo['height'] = 180
print( "demo data:{}".format(demo) )
print( "id of demo data:{}".format(id(demo)) )
# demo data:{'height': 180, 'weight': 58, 'age': 20}
# id of demo data:139675823957480
demo['name'] = 'Tom'
print( "demo data:{}".format(demo) )
print( "id of demo data:{}".format(id(demo)) )
# demo data:{'height': 180, 'weight': 58, 'age': 20, 'name': 'Tom'}
# id of demo data:139675823957480
del demo['age']
print( "demo data:{}".format(demo) )
print( "id of demo data:{}".format(id(demo)) )
# demo data:{'height': 180, 'weight': 58, 'name': 'Tom'}
# id of demo data:139675823957480