字典定義
1.字典是存儲信息的一種方式。
2.字典以鍵-值對存儲信息,因此字典中的任何一條信息都與至少一條其他信息相連。
3.字典的存儲是無序的,因此可能無法按照輸入的順序返回信息。
Python中定義字典
dictionary_name = {key_1: value_1, key_2: value_2}
為了更明顯的顯示數據,通常寫成下面的格式:
dictionary_name = {key_1: value_1,
key_2: value_2
}
字典的基本用法
定義一個字典:
把 list、dictionary、function 的解釋寫成一個字典,請按下面的格式輸出 dictionary 和 function 的定義
python_words = {'list': '相互沒有關系,但具有順序的值的集合',
'dictionary': '一個鍵-值對的集合',
'function': '在 Python 中定義一組操作的命名指令集',
}
print("\n名稱: %s" % 'list')
print("解釋: %s" % python_words['list'])
字典的基本操作
逐個輸出字典中的詞條過於麻煩,因此可以使用循環輸出
# name 和 meaning 可以隨意該名稱,試試改成 word 和 word_meaning
for name, meaning in python_words.items():
print("\n名稱: %s" % name)
print("解釋: %s" % meaning)
# 還有幾種其他的輸出方式,動手試一下。
print("***********************************************")
for word in python_words:
print("%s" % word)
print("***********************************************")
for word in python_words.keys():
print(word)
print("***********************************************")
for meaning in python_words.values():
print("值: %s" % meaning)
print("***********************************************")
for word in sorted(python_words.keys()):
print("%s: %s" % (word, python_words[word]))
給字典加入新的鍵-值對:
# 定義一個空字典
python_words = {}
# 給字典加入新項(詞條):使用 字典名[鍵名] = 值 的形式可以給字典添加一個鍵-值對
python_words['Joker'] ='會玩 LOL'
python_words['Burning'] = '會玩 DOTA'
python_words['Elingsama'] = '會玩爐石傳說'
def showMeanings(dictionary):
for name, meaning in dictionary.items():
print("\n名稱: %s" % name)
print("解釋: %s" % meaning)
修改字典中的值:
# 使用 字典名[鍵名] = 新值 的形式更改已經存在的鍵-值對
python_words['Joker'] = 'LOL 的惡魔小丑'
print('\nJoker: ' + python_words['Joker'])
刪除字典中的項:
# 返回 Joker 對應的值,同時刪除 Joker 的鍵-值對
_ = python_words.pop('Joker')
# 刪除 Buring 的鍵-值對
del python_words['Burning']
print(_)
修改鍵名:
# 1.創建一個新鍵 # 2.將要更換鍵名的值賦給新鍵 python_words['elingsama'] = python_words['Elingsama'] del python_words['Elingsama'] showMeanings(python_words
