字典定義
1.字典是存儲信息的一種方式财饥。
2.字典以鍵-值對存儲信息,因此字典中的任何一條信息都與至少一條其他信息相連钥星。
3.字典的存儲是無序的,因此可能無法按照輸入的順序返回信息贯莺。
Python 中定義字典
dictionary_name = {key_1: value_1, key_2: value_2}
為了更明顯的顯示數(shù)據(jù),通常寫成下面的格式:
dictionary_name = {key_1: value_1,
? ? ? ? ? ? ? ? ? key_2: value_2
? ? ? ? ? ? ? ? ? }
字典的基本用法
定義一個(gè)字典:
把 list撕蔼、dictionary鲸沮、function 的解釋寫成一個(gè)字典楣号,請按下面的格式輸出 dictionary 和 function 的定義
python_words = {'list': '相互沒有關(guān)系炫狱,但具有順序的值的集合',
? ? ? ? ? ? ? ? 'dictionary': '一個(gè)鍵-值對的集合',
? ? ? ? ? ? ? ? 'function': '在 Python 中定義一組操作的命名指令集',
? ? ? ? ? ? ? ? }
print("\n名稱: %s" % 'list')
print("解釋: %s" % python_words['list'])
字典的基本操作
逐個(gè)輸出字典中的詞條過于麻煩,因此可以使用循環(huán)輸出
# name 和 meaning 可以隨意該名稱酷含,試試改成 word 和 word_meaning
for name, meaning in python_words.items():
? ? print("\n名稱: %s" % name)
? ? print("解釋: %s" % meaning)
# 還有幾種其他的輸出方式,動(dòng)手試一下呀舔。
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]))
給字典加入新的鍵-值對:
# 定義一個(gè)空字典
python_words = {}
# 給字典加入新項(xiàng)(詞條):使用 字典名[鍵名] = 值 的形式可以給字典添加一個(gè)鍵-值對
python_words['Joker'] ='會(huì)玩 LOL'
python_words['Burning'] = '會(huì)玩 DOTA'
python_words['Elingsama'] = '會(huì)玩爐石傳說'
def showMeanings(dictionary):
? ? for name, meaning in dictionary.items():
? ? ? ? print("\n名稱: %s" % name)
? ? ? ? print("解釋: %s" % meaning)
修改字典中的值:
# 使用 字典名[鍵名] = 新值 的形式更改已經(jīng)存在的鍵-值對
python_words['Joker'] = 'LOL 的惡魔小丑'
print('\nJoker: ' + python_words['Joker'])
刪除字典中的項(xiàng):
# 返回 Joker 對應(yīng)的值省古,同時(shí)刪除 Joker 的鍵-值對
_ = python_words.pop('Joker')
# 刪除 Buring 的鍵-值對
del python_words['Burning']
print(_)
修改鍵名:
# 1.創(chuàng)建一個(gè)新鍵
# 2.將要更換鍵名的值賦給新鍵
python_words['elingsama'] = python_words['Elingsama']
del python_words['Elingsama']
showMeanings(python_words)
嵌套
嵌套包括把列表或字典放在另一個(gè)列表或字典中。
值為列表的字典
favorite_numbers = {'eric': [3, 11, 19, 23, 42],
? ? ? ? ? ? ? ? ? ? 'ever': [2, 4, 5],
? ? ? ? ? ? ? ? ? ? 'willie': [5, 35, 120],
? ? ? ? ? ? ? ? ? ? }
通過 字典名[詞條名][詞條內(nèi)位置] 訪問
print(favorite_numbers['eric'][0])
值為字典的字典
sparse_matrix = {}
sparse_matrix[0] = {1: 12.3, 23: 25.5}
sparse_matrix[1] = {3: 12.0, 15: 25.5}
# 打印出來看下上述字典的樣子
print('sparse_matrix = {')
for key, value in sparse_matrix.items():
? ? print(key,':',value)
print('}')
# 通過 字典名[詞條名][詞條內(nèi)屬性名] 訪問
print(sparse_matrix[0][23])
雖然一層嵌套很有用,但是隨著層級的增多白嘁,嵌套難度會(huì)增大。Python 中一些其他的結(jié)構(gòu)膘流,比如類絮缅,也可以有效的把數(shù)據(jù)組織成某種結(jié)構(gòu)鲁沥。如果從數(shù)據(jù)庫或者其他地方獲得了很深的嵌套數(shù)據(jù)画恰,處理起來就會(huì)很麻煩,因此盡量控制嵌套的深度很有必要。