# 經檢查,發現自己理解錯了需求,請忽略當前博文
《像計算機科學家一樣思考python》11.10練習中 練習 11-2
閱讀字典方法setdefault的文件,並使用它來寫乙個更簡潔的invert_dict
def invert_dict(n):輸出結果:# 返回乙個列表,第一項用setdefault查詢使用者輸入的單詞n是否存在,第二項返回查到項值
# 如果單詞(鍵)不存在,則在字典中新增鍵並將值設為預設值(這裡是none)
fin = open('words.txt')
words = dict()
count = 1
for line in fin:
word = line.strip()
words[word] = count
count += 1
return words.setdefault(n, none), words[n]
print(invert_dict('abc'))
(none, none)
(4452, 4452)
python內建字典 python中字典的內建方法
python字典包含了以下內建方法 功能 字典 clear 函式用於刪除字典內所有元素。語法 dict.clear 引數 無 返回值 沒有任何返回值。dict print 字典長度 d len dict 字典長度 2 dict.clear print 字典刪除後長度 d len dict 字典刪除後...
Python 中之字典
字典是另一種可變容器模型,且可儲存任意型別物件,如其他容器模型。字典由鍵和對應值成對組成。字典也被稱作關聯陣列或雜湊表。基本語法如下 dict 也可如此建立字典 dict1 dict2 每個鍵與值用冒號隔開 每對用逗號分割,整體放在花括號中 鍵必須獨一無二,但值則不必。值可以取任何資料型別,但必須是...
python中關於字典
ab print swaroop s address is s ab swaroop adding a key value pair ab guido guido python.org deleting a key value pair del ab spammer print nthere are...