特性
- Key-Value pairs
- Unordered (無順序的)
- Mutable (可改變的)
- Iterable (可疊代的)
Dictionary 建立
# Dictionary用{}將資料包住,且資料可以任一型態
dict1 = {}
dict2 = dict()
print(dict1) # {}
print(dict2) # {}
Person1 = {'Name':'Grace', 'age': 26, 'Height':172, 'Sex':'Male'}
number = ('a1', 'b2', 'c3', 'd4')
dict(number)
print(number) #{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
fruits = dict(Apple=20, Orange=15, Tomato=18)
print(fruits) #{'Apple':20, 'Orange':15, 'Tomato':18}
#用Type去檢查資料型態
print(type(Person1)) # <class 'dict'>
Dictionary Methods
#元素(elements)有幾個
dict3 = {'Name':'Grace', 'age': 26, 'Height':172, 'Sex':'Male'}
print(len(dict3)) # 4
#取出指定key的元素
print(dict3['Name']) # Grace
#可更改dict的內容
dict3['Name'] = 'Alice'
print(dict3) #{'Name': 'Alice', 'age': 26, 'Height': 172, 'Sex': 'Male'}
#新增
dict3['City'] = 'Taipei'
print(dict3) #{'Name': 'Alice', 'age': 26, 'Height': 172, 'Sex': 'Male', 'City': 'Taipei'}
#刪除
del dict3['City']
print(dict3) #{'Name': 'Alice', 'age': 26, 'Height': 172, 'Sex': 'Male'}
#清除資料
dict3.clear()
print(dict3) #{}
#利用key值去尋找value
dict4 = {'Name':'Grace', 'age': 26, 'Height':172, 'Sex':'Male'}
print(dict4.get('Sex')) #Male
#取得所有key值
print(dict4.keys()) #dict_keys(['Name', 'age', 'Height', 'Sex'])
#取得所有value值
print(dict4.values()) #dict_values(['Grace', 26, 172, 'Male'])
#取得所有item值
print(dict4.items())
#dict_items([('Name', 'Grace'), ('age', 26), ('Height', 172), ('Sex', 'Male')])
What can be a key?
- The key has to be immutable.
- The key has to be hashable.
以下資料型態可以當Key值
- Integers
- Float
- Boolean
- String
- Tuples