字典的宣告
變數名 { 鍵 : 值 }
variable_name { key : value }
1. 字典的宣告
>>> X = dict()
>>> id(X)
37383264
?
>>> X = { 'One':1,'Two':2,'Three':3 }
>>> X
{'One': 1, 'Two': 2, 'Three': 3}
>>> id(X)
34178464?
>>> X.values()
dict_values([1, 2, 3])
>>> X.keys()
dict_keys(['One', 'Two', 'Three'])
? 2. 字典查詢
>>> X['Two']
2
? 3. 字典元素個數
>>> len(X)
3
?4. 判斷 Key 或 Value 屬於 Dictionary 的元素
>>> 'Two' in X
True
>>> 'Four' in X
False
>>> 2 in X
False
>>> 2 in X.values()
True
5. 計算 Key 出現次數
>>> H = 'Python is pretty'
>>> def my_dictionary(H):
...???? D = dict()
...???? for C in H:
...??????? if C not in D:
...?????????? D[C] = 1
...??????? else:
...?????????? D[C] += 1
...???? return D
...
>>> X = my_dictionary(H)
>>> X
{'P': 1, 'y': 2, 't': 3, 'h': 1, 'o': 1, 'n': 1, ' ': 2, 'i': 1, 's': 1, 'p': 1,
?'r': 1, 'e': 1}
? 6. 字典遍歷
不按順序遍歷:
>>> for c in X:
...??? print(c,X[c])
...
1 one
2 two
3 three
4 four
5 five
按順序遍歷:
>>> for c in
sorted(X)
:
...???? print(c, X[c])
...
1 one
2 two
3 three
4 four
5 five
?
?7. 反向查詢: 由 Value 去查詢 Key
?>>> def reverse_lookup(d,v):
...???? for k in d:
...???????? if d[k] == v:
...???????????? return k
...???? raise LookupError()
...
?>>> X = {1:'one',2:'two',3:'three',4:'four',5:'five'}
>>> k = reverse_lookup(X,'two')
>>> k
2
>>> k = reverse_lookup(X,'Six')
Traceback (most recent call last):
? File "
? File "
LookupError
end
?
8. 字典 Dictionary 與列表 List
>>> def invert_dict(d):
...???? reverse = dict()
...???? for k in d:
...???????? val = d[k]
...???????? if val not in reverse:
...??????????? reverse[val] = [k]
...???????? else:
...??????????? reverse[val].append(k)
...???? return reverse
...
>>> h = {'a':1,'b':2,'c':1,'d':3,'e':1,'f':2}
>>> m = invert_dict(h)
>>> m
{1: ['a', 'c', 'e'], 2: ['b', 'f'], 3: ['d']}
?
參考
1. 像計算機科學家一樣思考 Python, [美] Allen B Downey 著,趙普明譯,中國工信出版集團 / 人民郵電出版社, ISDN 9787115425515
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
