• 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

  • 相关阅读:
    python 线程Queue 用法代码展示
    Python中的join()函数的用法
    python 中爬虫 content和text的区别
    免费代理ip爬虫分享
    django数据库的表已迁移的不能重新迁移的解决办法
    RuntimeError: Model class app_anme.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.---python学习错误记录
    MYSQL查询操作 详细
    mysql数据库的基本操作命令总结
    http短连接与长连接简介
    浅谈http协议
  • 原文地址:https://www.cnblogs.com/chingchangmeng/p/11388006.html
Copyright © 2020-2023  润新知