Python3 的字典

来源:https://www.cnblogs.com/PythonFCG/archive/2018/01/29/8379554.html
-Advertisement-
Play Games

1、dict() 字典 字典是python里唯一的映射類型 2、字典由key和value組成的項組成 如何創建一個字典: 3、字典的內置函數 keys values items copy clear get fromkeys update pop popitems setdefault 4、設計一個 ...


1、dict() 字典

字典是python里唯一的映射類型

2、字典由key和value組成的項組成

如何創建一個字典:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})

3、字典的內置函數

keys

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> for i in b.keys():
    print(i)

    
one
two
three

 

values

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> for i in b.values():
    print(i)

    
1
2
3

 

items

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> for i in b.items()
>>> for i in b.items():
    print(i)

    
('one', 1)
('two', 2)
('three', 3)

 

copy

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c=b.copy()
>>> c
{'one': 1, 'two': 2, 'three': 3}
>>> b['one']=4
>>> b
{'one': 4, 'two': 2, 'three': 3}
>>> c
{'one': 1, 'two': 2, 'three': 3}

 

clear

{'one': 1, 'two': 2, 'three': 3}
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> b.clear()
>>> b
{}

 

get

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> b.get('one')
1
>>> b.get(4)
>>> print(b.get(4))
None

 

fromkeys

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c=b.fromkeys("1",2)
>>> c
{'1': 2}

 

update

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c=b.fromkeys("1",2)
>>> c
{'1': 2}
>>> b.update(c)
>>> b
{'one': 1, 'two': 2, 'three': 3, '1': 2}

 

pop

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c=b.fromkeys("1",2)
>>> c
{'1': 2}
>>> b.update(c)
>>> b
{'one': 1, 'two': 2, 'three': 3, '1': 2}
>>> b.pop('1')
2
>>> b
{'one': 1, 'two': 2, 'three': 3}

 

popitems

 

b = {'one': 1, 'two': 2, 'three': 3}
>>> b.popitem()
('three', 3)

 

 setdefault

'''Help on built-in function setdefault:

setdefault(key, default=None, /) method of builtins.dict instance
    Insert key with a value of default if key is not in the dictionary.
    
    Return the value for key if key is in the dictionary, else default.'''

>>> b={}
>>> b.setdefault('1',2)
2
>>> b
{'1': 2}
>>> b['1']=3
>>> b.setdefault('1',2)
3
>>> b
{'1': 3}

 

4、設計一個通訊錄程式

print("|---歡迎進入通訊錄程式---|\n|---1.查詢聯繫人資料---|\
\n|---2.插入新的聯繫人---|\n|---3.刪除已有聯繫人---|\\n|---4.列印所有用戶信息---|\n|---5.退出通訊錄程式---|")

mydict={}
while 1:
    fun=input("\n請輸入相關指令代碼:")
    if fun=='2':
        name=input("請輸入聯繫人姓名:")#key
        if name in mydict:
            print("您輸入的用戶名已存在-->>",end='')
            print(name,':',mydict[name])
            yn=input("是否修改用戶資料(YES/NO):")
            if yn == "YES":
                number=input("請輸入用戶電話號碼:")#value
                mydict[name]=number
                continue
            else:
                continue    
        number=input("請輸入用戶電話號碼:")#value
        mydict[name]=number
        print('錄入成功!',name,':',mydict[name])
        continue
    elif fun=='1':
        name=input("請輸入聯繫人姓名:")#key
        if name in mydict:
            print(name,':',mydict[name])
            continue
        else:
            print("你查找的用戶不存在!")
            continue
    elif fun=='3':
        name=input("請輸入聯繫人姓名:")#key
        if name in mydict:
            print('用戶信息:',name,':',mydict[name])
            if mydict.pop(name,1)!=1:
                print('刪除成功!')
                continue    
        else:
            print("你刪除的用戶不存在!")
            continue
    elif fun=='5':
        print("---感謝使用通訊錄程式---")
        break
    elif fun=='4':
        for i in mydict:
            print(i,':',mydict[i],end='\n')
    else:
        print("請輸入正確指令!!!")
        continue
'''            
Help on built-in function pop:

pop(...) method of builtins.dict instance
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised        
'''    

5、設計一個用戶登陸程式

版本1

user={}
flag=0
flag1=0
flag2=0
while 1:
    if flag2==1:
        print("歡迎進入XXOO系統,請點擊右上角的X結束程式!")
        while 1:
            flag2==0
        
        
    print("\n|--- 新建用戶:N/n ---|\
           \n|--- 登陸賬號:E/e ---|\
           \n|--- 退出程式:Q/q ---|")
    fun=input("請輸入指令代碼:")
    while fun=='N'or fun=='n':
        if flag==1:
            name=input("此用戶名已被使用,請重新輸入:")
        else:
            name=input("請輸入用戶名:")
        if name not in user:
            flag=0
            print("用戶名可以使用!\n")
            pswd=input("請輸入密碼:")
            user[name]=pswd
            print("註冊成功,趕緊試試登陸吧!")
            break
        else :
            flag=1
            continue
    while fun=='E' or fun=='e':
        if flag1:
            name=input("您輸入的用戶名不存在請重新輸入:")
        else:
            name=input("請輸入用戶名:")      
        if name not in user:
            flag1=1
            continue
        else:
            flag1=0
            pswd=input('請輸入密碼:')
            if pswd==user[name]:
                flag2=1
                break
            else:
                print("密碼錯誤")
                break
    if fun=='Q' or fun=='q':
        print("|--- 感謝使用 ---|")
        break
            
        
            
        

版本2

user_data = {}

def new_user():
    prompt = '請輸入用戶名:'
    while True:
        name = input(prompt)
        if name in user_data:
            prompt = '此用戶名已經被使用,請重新輸入:'
            continue
        else:
            break

    passwd = input('請輸入密碼:')
    user_data[name] = passwd
    print('註冊成功,趕緊試試登錄吧^_^')

def old_user():
    prompt = '請輸入用戶名:'
    while True:
        name = input(prompt)
        if name not in user_data:
            prompt = '您輸入的用戶名不存在,請重新輸入:'
            continue
        else:
            break
    
    passwd = input('請輸入密碼:')
    pwd = user_data.get(name)
    if passwd == pwd:
        print('歡迎進入XXOO系統,請點右上角的X結束程式!')
    else:
        print('密碼錯誤!')

def showmenu():
    prompt = '''
|--- 新建用戶:N/n ---|
|--- 登錄賬號:E/e ---|
|--- 推出程式:Q/q ---|
|--- 請輸入指令代碼:'''

    while True:
        chosen = False
        while not chosen:
            choice = input(prompt)
            if choice not in 'NnEeQq':
                print('您輸入的指令代碼錯誤,請重新輸入:')
            else:
                chosen = True

        if choice == 'q' or choice == 'Q':
            break
        if choice == 'n' or choice == 'N':
            new_user()
        if choice == 'e' or choice == 'E':
            old_user()

showmenu()

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在面向對象編程的過程中,我們很容易通過繼承、多態來解決縱向擴展。 但是對於橫向的功能。面向對象的是無法解決的。所以AOP——面向切麵編程其實是面向對象編程思想的一個補充。過濾器和攔截器是AOP思想的具體實現,本文講解了在Spring boot下對過濾器和攔截器的使用。 ...
  • 工程報錯:java.lang.NoClassDefFoundError 名稱:類文件衝突 原因: 問題1,Windows 系統在某些時候不區分大小寫,比如Windows會認為Test.class 和test.class 是一個文件,無法區分。 問題2,在項目工程中有多個源碼包(source fold ...
  • 作為一個前端專業的人來說,對於事務的理解,一直停留在“要麼都成功,要麼都不成功”的小白階段。既然自己將2018年定義為”深入理解“的一年,那麼就從深入理解事務開始吧。 ...
  • dubbo消費者調用服務超時的原因可能有很多,今天排查問題花了兩個小時,也查了很多資料,好像每一篇資料都是提出一個問題,所以簡單總結幾點: 1. 配置才是重中之重,仔細檢查服務提供方的dubbo service和消費者的dubbo reference。保證服務方暴露介面和ref對象正確,保證消費者引 ...
  • 圖形用戶界面( G raphical U ser I nterface,GUI)編程 Python2.0級以下的版本叫做Tkinter,Python3.0改名為tkinter tkinter 模塊:添加 Tk 到應用中 那麼為了讓 tkinter 成為應用的一部分,你需要做些什麼呢?首先,已經存在的 ...
  • 一、int轉換成string Ⅰ、to_string函數 c++11標準增加了全局函數std::to_string: string to_string (int val); string to_string (long val); string to_string (long long val); ...
  • 空間配置器(allocator)這個概念在閱讀源碼之前我根本沒有聽過,原以為記憶體分配都是使用new和delete運算符(註意和operator new、placement new、operator delete以及placement delete不同)。在實際使用STL編程時也很少會遇到自己去實現一 ...
  • 如何用腳本判斷用戶輸入的的字元串是下麵的時間格式2004-11-21 必須要保證用戶的輸入是此格式,並且是時間,比如說月份不大於12等等,另外我需要用戶輸入兩個,並且後一個要比前一個晚,只允許用JAVASCRIPT,請詳細幫助作答, 提示:可用正則表達式提前判斷一下格式,然後提取各時間欄位內容 寫出 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...