Dictionary 字典
在字典裡,皆由key(鍵)和value(值)組成
dict = {key1 : value1, key2 : value2 }
kaka = {'firstname':'lin', 'age': 28, 'height': 175}
print(kaka)
{'firstname': 'lin', 'age': 28, 'height': 175}
取得 Dictionary 裡有幾個元素: len()
print(len(kaka))
[Out]: 3
取得 Dictionay 裡的資料
透過key
來取得相對應的value
dict[key] -> return value
kaka['age']
[Out]: 28
取得 Dictionary 裡的所有 key
dict.keys()
kaka.keys()
dict_keys(['firstname', 'age', 'height'])
取得 Dictionary 裡的所有 value
dict.values()
kaka.values()
dict_values(['lin', 28, 175])
取得 Dictionary 裡的所有資料
dict.items()
kaka.items()
dict_items([('firstname', 'lin'), ('age', 28), ('height', 175)])
增加 Dictionary 裡的資料
dict[new_key] = value
kaka['weight'] = 68
kaka
{'firstname': 'lin', 'age': 28, 'height': 175, 'weight': 68}
更新 Dictionary 裡的資料
dict[key] = new_value
kaka['weight'] = 70
kaka
{'firstname': 'lin', 'age': 28, 'height': 175, 'weight': 70}
移除 Dictionary 裡的資料
del method
del dict[key]
del kaka['weight']
kaka
{'firstname': 'lin', 'age': 28, 'height': 175}
pop method
dict.pop(key)
kaka['weight'] = 70
kaka
{'firstname': 'lin', 'age': 28, 'height': 175, 'weight': 70}
kaka.pop('weight')
kaka
{'firstname': 'lin', 'age': 28, 'height': 175}
檢查指定的key是否存在於Dictionary中
key in dict -> return True 或是 False
'firstname' in kaka
[Out]: True
'weight' in kaka
[Out]: False
Dictionary 與 for-loop
for k, v in kaka.items():
print('{}: {}'.format(k, v))
firstname: lin
age: 28
height: 175
用 for-loop 來建立 Dictionary
temp = {}
for i in range(10):
temp[i] = i ** 2
temp
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
pyhonic
a = {x: x ** 2 for x in range(10)}
a
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}