這邊以動物種類跟數量為例,
宣告一個animal的dict:
範例: animal = {'動物名稱':數量}
animal = {'dog':100, 'cat':58, 'cow':254} print(animal) |
輸出結果:
{'dog':100, 'cat':58, 'cow':254}
變更dict內的參數值:
假設將dog參數設定為999
animal = {'dog':100, 'cat':58, 'cow':254} animal['dog'] = 999 print(animal) |
輸出結果:
{'dog':999, 'cat':58, 'cow':254}
新增dict的項目:
假設加入bird數量為549
animal = {'dog':100, 'cat':58, 'cow':254} animal['bird'] = 549 print(animal) |
輸出結果:
{'dog':100, 'cat':58, 'cow':254, 'bird':549}
刪除dict的項目:
以刪除cat項目為例
animal = {'dog':100, 'cat':58, 'cow':254} del animal['cat'] print(animal) |
輸出結果:
{'dog':100, 'cow':254}
將兩個dict合併:
第一個dict為animal,
第二個dict為other,
animal = {'dog':100, 'cat':58, 'cow':254} other = {'bird': 549, 'monkey':1007} animal.update(other) print(animal) |
輸出結果:
{'dog':100, 'cat':58, 'cow':254, 'bird':549, 'monkey':1007}
取得dict的所有項目或所有參數值:
animal = {'dog':100, 'cat':58, 'cow':254} print('animal items: ', animal.keys()) print('animal values: ', animal.values()) print(animal.items()) |
輸出結果:
animal items: dict_keys(['dog', 'cat', 'cow'])
animal values: dict_values([100, 58, 254])
dict_items([('dog', 100), ('cat', 58), ('cow', 254)])
獲取dict的特定項目或參數值:
animal = {'dog':100, 'cat':58, 'cow':254} x = [i for i in animal.keys()] y = [i for i in animal.values()] z = [i for i in animal.items()] print('animal items: ', x[0]) print('animal values: ', y[0]) print(z[0]) |
輸出結果:
animal items: dog
animal values: 100
('dog', 100)
留言列表