Python 字典 Dictionary

字典的宣告

變數名 { 鍵 : 值 }

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 "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in reverse_lookup
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

 

posted @ 2019-08-21 15:48  太川  阅读(125)  评论(0编辑  收藏  举报