1. 程式人生 > >《零基礎入門學習Python》(25)--字典:當索引不好用時(1)

《零基礎入門學習Python》(25)--字典:當索引不好用時(1)

前言

接下來講講字典的使用方式。

知識點

字典屬於對映型別。

列表,元祖,字串等屬於序列型別

  • 建立及訪問字典

 

>>> brand = ['abc','abcd','abcde','abcdef']
>>> solgan =  ['singe','range','reverse','pop']
>>> print('xxxx: ',solgan[brand.index('abcd')])
xxxx:  range
#下面是字典的建立,上面是用函式模擬
>>> dict1 = {'abc':'singe','abcd':'range','abcde':'reverse','abcdef':'pop'}
>>> print(dict1['abc'])
singe
>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2[3]
'three'
  • 建立一個空字典
#建立一個空字典:

>>> dict1 = {}
>>> dict1
{}
#或者
>>> dict3 = dict()
>>> dict3
{}
  • 建立字典的一些其他方法
  • dict(mapping)從對映物件(key,value)中初始化的新字典,例如:

>>> dict4 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
>>> dict4
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
# mapping可以是列表,也可以是元祖
>>> dict1 = dict((['F',70],['i',105],['s',115],['h',104],['C',67]))  
>>> dict1        
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
  • dict(**kwargs)用關鍵字引數列表中的name = value對初始化的新字典。 例如:
>>> dict4=dict(abc='python',abcd='c++')
>>> dict4
{'abc': 'python', 'abcd': 'c++'}
  • 直接給字典的key賦值和新增新的元素:

>>> dict4['abc']='C#'
>>> dict4
{'abc': 'C#', 'abcd': 'c++'}
>>> dict4['abcde']='C primer plus'
>>> dict4
{'abc': 'C#', 'abcd': 'c++', 'abcde': 'C primer plus'}
>>> 

課後習題

測試題

  • 嘗試一下將資料('F':30,'C':67,'h':104,'i':105,'s':115)建立為一個字典並訪問鍵’C’對應值

>>> MyDict = dict((('F', 70), ('i',105), ('s',115), ('h',104), ('C',67)))
>>> MyDict_2 = {'F':70, 'i':105, 's':115, 'h':104, 'C':67}
>>> type(MyDict)
<class 'dict'>
>>> type(MyDict_2)
<class 'dict'>
>>> MyDict['C']
67
  • 用方括號[]括起來的資料我們叫列表,那麼使用大括號{}括起來的資料我們就叫字典,對嗎?
>>> a = {1, 2, 3, 4, 5}
>>> type(a)
<class 'set'>

不難發現,雖然我們用大括號{}把一些資料括起來了,但由於沒有反映出這些資料有對映的關係,所以創建出來的不是字典,而是叫set的東西

  • 你如何理解有些字典做得到,但“萬能的”列表卻難以實現?
#舉個例子
>>> brand = ['李寧', '耐克', '阿迪達斯', '魚C工作室']
>>> slogan = ['一切皆有可能', 'Just do it', 'Impossible is nothing', '讓程式設計改變世界']
>>> print('魚C工作室的口號是:', slogan[brand.index('魚C工作室')])
魚C工作室的口號是: 讓程式設計改變世界

列表brand,slogan的索引和相對的值是沒有任何關係的,我們可以看出唯一有聯絡的就是兩
個列表間,索引號相同的元素是有關係的,所以這裡我們通過brand.index('魚C工作室')這樣的
語句,間接的實現通過品牌查詢對應的口號的功能。

這確實是一種可實現方法,但用起來,多少有些彆扭,效率還不高。況且Python是以簡潔為主,
這樣子的實現肯定是不能讓人滿意的,我們需要有字典這種對映型別的出現:

>>> dict1 = {'李寧':'一切皆有可能', '耐克':'Just do it', '阿迪達斯':'Impossible is nothing', '魚C工作室':'讓程式設計改變世界'}
>>> print('魚C工作室的口號是:', dict1['魚C工作室'])
魚C工作室的口號是: 讓程式設計改變世界
  • 下邊這些程式碼,他們都在執行一樣的操作嗎?你看得出差別嗎
>>> a = dict(one=1, two=2, three=3)
>>> a        
{'one': 1, 'two': 2, 'three': 3}

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> b    
{'one': 1, 'two': 2, 'three': 3}

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

>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> d
{'two': 2, 'one': 1, 'three': 3}

>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> e
{'three': 3, 'one': 1, 'two': 2}
  • 如圖,你可以推測出打了馬賽克部分的程式碼嗎? 

#利用字串的分割方法。
data = '1000,小甲魚,男'
MyDict = {}
(MyDict['id'],MyDict['name'],MyDict['sex']) = data.split(',')
print("ID:    " + MyDict['id'])
print("Name:  " + MyDict['name'])
print("Sex:   " + MyDict['sex'])
ID:    1000
Name:  小甲魚
Sex:   男

動動手

  • 嘗試利用字典特性編寫一個通訊錄程式吧,功能如圖:

#這個程式其還可以複雜一點就是每個if後面都加一個判斷是否輸入正確
#這裡個字典賦值的方法就是前面講過的——直接給字典的key賦值和新增新的元素
print('---歡迎進入通訊錄程式---')
print('---1.:查詢聯絡人資料---')
print('---2.:插入新的聯絡人---')
print('---3.:刪除已有聯絡人---')
print('---4.:退出通訊錄程式---')

txl=dict()


while True:
    
    temp = input('根據提示,請輸入你想做的事情!!!!!:')
    while not temp.isdigit():
        print('請重新輸入::::')
        temp = input('根據提示,請輸入你想做的事情!!!!!:')
        
    instr=int(temp)
    if instr == 1:
        name = input('請輸入聯絡人姓名')
        if name in txl:
            print(name + ':' + txl[name])
        else:
            print('您輸入的姓名不在通訊錄中!')
    elif instr == 2:
        name = input('請你想插入的聯絡人姓名: ')
        if name in txl:
            print('您輸入的姓名已存在 -->>',end='')
            print(name + ':' + txl[name])
            if input('是否修改使用者資料(YES/NO):').upper() == 'YES':
                txl[name] = input('請輸入使用者聯絡電話:')
        else:
            txl[name] = input('請輸入使用者聯絡電話:')
   
    elif instr == 3:
        name = input('請輸入聯絡人姓名:')
        if name in txl:
            del(txl[name])
        else:
            print('您輸入的聯絡人不存在。')

    elif instr == 4:
        break
    else:
        print('輸入錯誤,重新執行程式!!!!')

print('|--- 感謝使用通訊錄程式 ---|')