是一種無序性(unordered)
的key-value pair。主要由key
和value
的概念組成,在別的語言中通常稱為associative arrays
。
以下從宣告、操作、特性、常用方式做個紀錄。
宣告dictionary有幾種手法
from pprint import pprint
# brackets
demo = { 'height': 170, 'weight': 58, 'age': 20 }
pprint(demo)
print( "type of demo: {}".format( type(demo) ) )
# {'age': 20, 'height': 170, 'weight': 58}
# type of demo: <class 'dict'>
# dict
demo2 = dict( [('height', 180), ('weight', 68), ('age', 22)] )
pprint(demo2)
print( "type of demo2: {}".format( type(demo2) ) )
# {'age': 22, 'height': 180, 'weight': 68}
# type of demo2: <class 'dict'>
demo3 = dict(height=190, weight=90, age=25)
pprint(demo3)
print( "type of demo3: {}".format( type(demo3) ) )
# {'age': 25, 'height': 190, 'weight': 90}
# type of demo3: <class 'dict'>
# dictionary comprehension
generator = [x for x in range(10)]
demo4 = {x: x**2 for x in generator}
pprint(demo4)
print( "type of demo4: {}".format( type(demo4) ) )
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# type of demo4: <class 'dict'>