iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 10
0

概觀(Overview)

是一種無序性(unordered)的key-value pair。主要由keyvalue的概念組成,在別的語言中通常稱為associative arrays

以下從宣告、操作、特性、常用方式做個紀錄。

宣告(Declaration)

宣告dictionary有幾種手法

  • brackets
  • dict()
  • dictionary comprehension
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'>

參考


上一篇
Day9-String-Format
下一篇
Day11-Dictionary-操作
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言