Python 字典

給 MATLAB 使用者的 Python

Justin Kiggins

Product Manager

什麼是字典?

  • 類似 MATLAB 的結構陣列
  • 由 key:value 配對組成
  • 不保證有序
給 MATLAB 使用者的 Python

從字典取值

type(definitions)
dict
print(definitions['aardvark'])
A nocturnal burrowing mammal with long ears, a tubular snout, and a long 
extensible tongue, feeding on ants and termites. Aardvarks are native to 
Africa and have no close relatives.
給 MATLAB 使用者的 Python

建立字典

# Create a dictionary
dog = {'name': 'Toby', 'breed': 'Basset Hound'}
給 MATLAB 使用者的 Python

加入資料到字典

# Add more key:value pairs
dog['weight (lbs)'] = 552.3
dog['birthdate'] = "2016-06-26"
print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 552.3, 
 'birthdate': '2016-06-26'}
給 MATLAB 使用者的 Python

更新字典

# Update weight value
dog['weight (lbs)'] = 52.3

print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 52.3,
 'birthdate': '2016-06-26'}
給 MATLAB 使用者的 Python

從字典移除資料

dog.pop('birthdate')
print(dog)
{'name': 'Toby',
 'breed': 'Basset Hound',
 'weight (lbs)': 52.3}
給 MATLAB 使用者的 Python

一起來練習吧!

給 MATLAB 使用者的 Python

Preparing Video For Download...