一些字典的基本操作
.items()
.keys()
.values()
.get(self, key, dafault)
sorted() 該對字典進行排序的時候,返回的是列表
import operator
#字典
#使用花括號定義 a = {...}
#key-value (value可以是任意數據類型)
def base_operate():
alien = {'color': 'yellow', 'points': 5}
print(alien['color'])
print(alien['points'])
#print(alien['3']) #報錯 KeyError: '3'
#print(alien[0]) #不可以使用下標訪問
#添加key-value
alien['head'] = "so big"
print(alien['head'])
#刪除字典中的元素
del(alien['points'])
print(alien)
#遍歷字典
# 字典不關心鍵—值對的存儲順序, 而只跟蹤鍵和值之間的關聯關係
print(alien.items()) # 返回一個 鍵—值對 列表
for key, value in alien.items():
print(key + ": " + value)
print(alien.keys()) # 返回一個 鍵 列表
for key in alien.keys():
print(key)
print(len(alien.keys())) # 2
# not in
# if "hand" not in alien.keys():
# alien["hand"] = 2
# print(alien["hand"]) # 2
alien["hand"] = 3
#.get(self, key, default)
alien["hand"] = alien.get("hand", 2)
print(alien["hand"]) # 如果沒有alien["hand"] = 3這一句, 那麼輸出2, 否則輸出3
#按 key 順序遍歷字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
#遍歷 value
for value in favorite_languages.values():
print(value)
#對字典進行排序 !!!!!!!
nation = {"china": 200, 'usa': 300, "japan": 100}
# key爲函數,指定取待排序元素的哪一項進行排序
# operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據,參數爲一些序號(即需要獲取的數據在對象中的序號)
sortedNation = sorted(nation.items(), key = operator.itemgetter(1))
print(type(sortedNation)) # <class 'list'>
print(sortedNation) # key = operator.itemgetter(1) 時 [('japan', 100), ('china', 200), ('usa', 300)]
#print(sortedNation) # key = operator.itemgetter(0) 時 [('china', 200), ('japan', 100), ('usa', 300)]
print(sortedNation[0][0]) # china
def main():
base_operate()
if __name__ == "__main__":
main()