iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

操作層面分為取出資料、如何走訪和如何異動資料

取出資料

利用key的值取出相對應的value,可以使用中括號(square brackets)或是dict.get(key)存取。

這兩種方式主要差異在於當key不存在於dict時所引發的行為,中括號會拋出KeyError而dict.get(key)則會回傳None。若想傳回預設值,可以使用get(key, default)

而要判斷key是否存在於該dict中的話可以使用in

demo = { 'height': 170, 'weight': 58, 'age': 20 }

# square brackets
print( "height is {}".format(demo['height']) )
try:
    name = demo['name']
    print( "name is {}".format(name) )
except KeyError as e:
    print( "KeyError: {} does not exist".format(e) )

# height is 170
# KeyError: 'name' does not exist


# dict.get(key)
print( "height is {}".format(demo.get('height')) )
name = demo.get('name')
print( "name: {}".format(name) )
name = demo.get('name', 'Tom')
print( "name: {}".format(name) )

# height is 170
# name: None
# name: Tom


# check key if exist
if 'height' in demo:
    print( "height is {}".format(demo['height']) )
else:
    print( "height not found" )

if 'name' in demo:
    print( "name is {}".format(demo['name']) )
else:
    print( "name not found" )

# height is 170
# name not found

走訪

for加上in搭配以下其中一個

  • dict.keys()
  • dict.values()
  • dict.items()
demo = { 'height': 170, 'weight': 58, 'age': 20 }

# iteration
for what in demo:
    print( "what is {}".format(what) )

# what is height
# what is weight
# what is age


for key in demo.keys():
    print( "key is {}".format(key) )
    print( "type of key is {}".format(type(key)) )

# key is height
# type of key is <class 'str'>
# key is weight
# type of key is <class 'str'>
# key is age
# type of key is <class 'str'>


for value in demo.values():
    print( "value is {}".format(value) )
    print( "type of value is {}".format(type(value)) )

# value is 170
# type of value is <class 'int'>
# value is 58
# type of value is <class 'int'>
# value is 20
# type of value is <class 'int'>


for key, value in demo.items():
    print( "key is {}".format(key) )
    print( "value is {}".format(value) )

# key is height
# value is 170
# key is weight
# value is 58
# key is age
# value is 20

異動資料

demo = { 'height': 170, 'weight': 58, 'age': 20 }

# modification
print( "demo data before modification:{}".format(demo) )
demo['height'] = 180
demo['name'] = 'Tom'
del demo['age']
print( "demo data after modification:{}".format(demo) )

# demo data before modification:{'height': 170, 'weight': 58, 'age': 20}
# demo data after modification:{'height': 180, 'weight': 58, 'name': 'Tom'}

參考


上一篇
Day10-Dictionary-宣告
下一篇
Day12-Dictionary-特性
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言