YuKai0928
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- ###### tags: `資訊之芽` --- # Dictionary ![](https://i.imgur.com/rPf3fx5.png =30%x) src: chainsaw man 資芽北區2023 講師YuKai 洪郁凱 ---- # Outline - Before Dict - What is Dict - How do Dict works - Usage - Some Combo Skills --- # Before Dict 你應該要知道: - 利用學過的資料型別存資料 - 如何存取List/Tuple的元素 --- # What is Dict Dictionary 字典 用大括號來宣告 ```python= ex_dict = {"bday": 928, "name": "Kain"} #這裡以字串:數字為例 print(ex_dict) ``` ---- # What is Dict 用其他的方式來宣告 ```python= ex_dict = dict([["bday", 928], ["name", "Kain"]]) #傳入一個List/Tuple # 每個元素為一個鍵值對 可用List/Tuple ``` ---- # What is Dict Dictionary 字典 用大括號來宣告 最大的特色是可以用數字之外的物件來取值 ```python= ex_dict = {"bday": 928} #這裡以字串為例 ex_list = [928] print(ex_list["bday"], ex_list[0]) ``` <!-- .element: class="wrap-code" --> Key-Value Pairs 鍵值對 ---- # What is Dict |Key-Value|Index| |---|---| |一月 -> Jan |0 -> Jan| |二月 -> Feb |1 -> Feb| |九月 -> Sep |8 -> Sep| ```python= mon_list = ["Jan", "Feb", "Mar", ..., "Sep"] mon_dict = {"一月": "Jan", "二月": "Feb", "三月": "Mar", "九月": "Sep"} print(mon_list[0], mon_dict["一月"]) ``` <!-- .element: class="wrap-code" --> ---- # What is Dict 萬一資料不是有順序的呢? ```python= location_dict = {"台北": "Taipei", "桃園": "Taoyuan"} ``` ---- # What is Dict ```python= ex_dict = {"Mutated": "變異的", "Crab": "螃蟹"} print(ex_dict["Mutated"]) #一個長得很像字典的範例 print(ex_dict["變異的"]) # 不能反向! print(ex_dict["Dior"]) # 不能找沒在字典裡面的 ``` 最後兩行會導致Key Error 都是因為字典內沒有對應Key導致 ---- # Practice 用三種方式宣告一個字典 ```python= keys_list = ["名字", "屬性", "顏色"] value_list = ["皮卡丘", "雷系", "顏色"] ``` ---- # Practice 用三種方式宣告一個字典 ```python= keys_list = ["名字", "屬性", "顏色"] value_list = ["皮卡丘", "雷系", "顏色"] # Hints: # 用大括號 # 用dict()及雙層list # (bonus) ``` --- # How do Dict works Key值可以不只是字串 ```python= ex_tuple = (9, 2, 8) ex_dict = {ex_tuple: 928928} #用Tuple也可以 print(ex_dict[ex_tuple]) ``` ---- # How do Dict works Dict 是用一個酷東西["Hash"](https://thepythoncorner.com/posts/2020-08-21-hash-tables-understanding-dictionaries/)來實作的 這裡是參考資料 不會講 ---- # How do Dict works Hashable: String, Tuple, Numbers, Frozen Set, Lambda Function(?) 好玩的[參考資料](https://www.geeksforgeeks.org/why-and-how-are-python-functions-hashable/) --- # Usage 新增,修改,刪除,迭代 ---- # Usage 新增 ```python= info = {} info["Kain"] = 928 print(info["Kain"]) ``` ---- # Usage 修改 ```python= info = {"Kain": 928} info["Kain"] = "B09" print(info["Kain"]) ``` ---- # Usage 刪除 ```python= info = {"Kain":928} info.pop("Kain") print("Kain" in info) ``` ---- # Usage 刪除 ```python= info = {"Kain": 928} del info["Kain"] print("Kain" in info) # 確認 "Kain"-928 還在不在 ``` ---- # Usage 全部刪除! ```python= info = {"Kain":928, ""} info.clear() ``` ---- # Usage 迭代 ```python= calories = {"apple":243, "banana":132, "candy":432} for i in calories: print(i) ``` for會迭代Key:Value裡面的Key ---- # Usage 迭代(Key) ```python= calories = {"apple":243, "banana":132, "candy":432} for i in calories.keys(): print(i) ``` ---- # Usage 迭代(Value) ```python= calories = {"apple":243, "banana":132, "candy":432} for i in calories.values(): print(i) ``` ---- # Usage 迭代(Key,Value) ```python= calories = {"apple":243, "banana":132, "candy":432} for i in calories.items(): print(i) ``` 會將 (Key,Value) 組合成Tuple來迭代 ---- # Usage 合併兩個字典 ```python= dict_a = {"學校": "CKHS", "年級": "10th"} dict_b = {"類組": "三", "校排": "10%"} dict_c = merge(dict_a,dict_b)??? #這是psudo-code 不要記 ``` ---- # Usage 合併兩個字典 用update 用*星*號*爆*開 ```python= dict_c = {**dict_a, **dict_b} # c為合併後的字典 dict_a.update(dict_b) # a為合併後的字典 #暴雷:之後可以用星號 *list_a / **dict_a 炸開並傳入func當作參數 ``` --- # Combo Skills 處理Key Error ---- # Combo Skills What is Key Error ```python= student = {} student["Kain"] = "B09" print(student["Jolin"]) ``` ---- # Combo Skills 先檢查再取值 ```python= if "Jolin" in student: print(student["Jolin"]) ``` ---- # Combo Skills 也可以用Method ![](https://i.imgur.com/RHxCAwc.png) ```python print(student.get("Jolin")) ``` --- # Method 大全 ![](https://i.imgur.com/3CORHq8.png) ```python= help(dict) # 按q退出 ``` ---- # Quiz 1. 給定任意Dict 請輸出一個Key-Value對調的dict (要比下面的更好) 2. 給出一個Dict 把下面的版本弄壞 ```python= ans_dict = dict() for k,v in given_dict.item(): ans_dict[v] = k ``` --- # Set ```python= ex_tuple = (928,) ex_list = [928,] ex_dict = {"bday": 928} ex_set = {928} ``` ---- # Set - unordered - hashable elements only - mutable - frozenset for immutable usage - NO duplicated elements ---- # Set ```python= dict_a = {} set_a = set(["Vokda","Rum","Gin","Orange Juice"]) set_a.add("Tequila") set_a.remove("Orange Juice") ``` ---- # Set ![](https://i.imgur.com/hmAVl54.png) src : [learnbyexample](https://www.learnbyexample.org/python-set/) ---- # Set Union ```python= set_a = {1, 2, 3, 5, 8, 13} set_b = {2, 3, 5, 7, 11, 13} print(set_a.union(set_b)) print(set_a | set_b) # Elegant! ``` ---- # Set Intersection ```python= set_a = {1, 2, 3, 5, 8, 13} set_b = {2, 3, 5, 7, 11, 13} print(set_a.intersection(set_b)) print(set_a & set_b) # Elegant! ``` ---- # Set Difference ```python= set_a = {1, 2, 3, 5, 8, 13} set_b = {2, 3, 5, 7, 11, 13} print(set_a.difference(set_b)) print(set_a-set_b) # Elegant! ``` ---- # Set Symmetric Difference ```python= set_a = {1, 2, 3, 5, 8, 13} set_b = {2, 3, 5, 7, 11, 13} print(set_a.symmetric_difference(set_b)) print(set_a^set_b) # Elegant! ``` ---- # Set ![](https://i.imgur.com/9Zw9FSU.png) src: Spy X Family --- # Homework [3035](https://neoj.sprout.tw/problem/3035) [3036](https://neoj.sprout.tw/problem/3036) --- # Hash 雜湊函式(Hash Function) ``` hash(obj, /) Return the hash value for the given object. Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true. ``` ---- # Function ---- f(x) = 9 x + 28 f(100) = 928 f(3) = ? f(?) = 73 ---- 定義妥善的f需要有 - 定義域/值域 - 好的演算法 e.g. $\sin(x), \tan(x)$ ---- # Hash Function 好的Hash Function需要有 - hard to reverse - easy to compute - $x=y \leftrightarrow h(x) = h(y)$ - Given $h(x)$, hard to find $x$ e.g. SHA256 SHA512 ---- # Hash Function - 保護密碼 - 將定義域的東西壓進值域 - 誰是臥底(?) ---- # Hash Function ```python= f(x) = x%17 g(x) = 2x + 3 ``` ---- # Hash Fucntion ```python= f(x) = x裡字母a的數量 ``` ----

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully