10.Python學習之字典的使用方法

        字典(dictionary)是Python中另一個非常有用的內置數據類型。列表、元組都是有序的對象集合,字典是無序的對象集合。兩者之間的區別在於:字典當中的元素是通過鍵來存取的,而不是通過偏移存取(即可以通過索引來讀取)。

        字典是一種映射類型,字典用"{ }"標識,它是一個無序的鍵(key) : 值(value)對集合。鍵(key)必須使用不可變類型。在同一個字典中,鍵(key)必須是唯一的。

1.字典的創建:

我們需要注意的是:

1)字典是一個無序的數據集合,使用print輸出字典的時候
2)通常輸出的順序和定義的順序是不一致的

1)創建字典的一般方法:

#創建字典的一般方法
#字典:key - value 鍵值對
#value可以是任意數據類型
s = {
    'Linux':[100,99,88],
    'Python':[190,564,645]
}

print(s,type(s))

結果:

                                                    

2)空字典的創建:

s = {}
print(type(s))

結果:          

                                        

3)工廠函數:

#工廠函數
d = dict()
print(type(d))

d1 = dict(a=1,b=2)
print(d1,type(d1))

結果:

                                                     

4)字典的嵌套:

字典中可以嵌套字典,已達到我們想要表達的目的:

#字典的嵌套
students = {
    '03164067':{
        'name':'wf',
        'age':21,
        'score':80
    },
    '03164068':{
        'name': 'lee',
        'age': 22,
        'score': 59
    }
}
print(students['03164067']['name'])

結果:

                                 

 

5)多值映射:

#所有的key對應的value值是一樣的
print({}.fromkeys({'1','2'},'000000'))

結果:

                                            

2.字典的特性:

d = {
    '1':'a',
    '2':'b'
}
#成員操作符
print('1' in d)

#for循環,默認遍歷字典的key值
for i in d:
    print(i)

#遍歷字典
for i in d:
    print(i,d[i])

結果:

                                     

3.字典的增加:

#增加一個元素
#如果key值存在,則更新對應的value值
#如果key值不存在,則添加對應key-value
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services['mysql'] = 3306
print(services)

services['http'] = 443
print(services)

結果:

                                                         

 添加多個鍵值對:

#添加多個key-value值
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services_backup = {
    'https':443,
    'tomcat':8080,
    'http':8080
}
services.update(services_backup)
print(services)

services.update(flask=9000,http=8000)
print(services)

結果:

                                       

setdefault添加key值:
#setdefault添加key值
#如果key值存在,不做修改
#如果key值不存在,添加對應的key-value
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

services.setdefault('http',9090)
print(services)

services.setdefault('oracle',44575)
print(services)

結果:

                                            

4.字典的刪除:

1)從內存中刪除:

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)
del services['http']
print(services)

結果:

                                           

2)pop刪除指定元素:

#pop刪除指定key的key-value
#如果不存在,報錯
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

item = services.pop('http')      #如果key存在,刪除,並返回刪除key對應的value
print(item)
print(services)

結果:

                                                     

3)popitem刪除最後一個元素:

#popitem刪除最後一個key-value值
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

item = services.popitem()
print('刪除的是:',item)
print(services)

結果:

                                                   

4)清空字典內容

#清空字典內容
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
print(services)

services.clear()
print(services)

結果:

                                                  

5.字典的查看:

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

#查看字典的key值
print(services.keys())

#查看字典的value值
print(services.values())

結果:

                                           

services = {
    'http':80,
    'ftp':21,
    'ssh':22
}

#查看字典的key-value值
print(services.items())

#查看key的value值
#key不存在,默認返回none
#key不存在,有default值,則返回default值
print(services.get('http'))
print(services.get('https','key not exist'))

結果:

                                          

#遍歷
services = {
    'http':80,
    'ftp':21,
    'ssh':22
}
for k,v in services.items():
    print(k,'--->',v)

for k in services:
    print(k,'--->',services[k])

結果:

                                               

6.字典綜合練習:

 重複的單詞: 此處認爲單詞之間以空格爲分隔符, 並且不包含,和.>;
    # 1. 用戶輸入一句英文句子;
    # 2. 打印出每個單詞及其重複的次數;
 "hello java hello python"
# hello 2
# java 1
# python 1
s = input('s:')

#1.把每個單詞分割處理
s_li = s.split()
print(s_li)

#通過字典存儲該單詞和其出現的次數

word_dict = {}

"""
依次循環遍歷列表
    如果列表元素不在字典的key中,將元素作爲key 1作爲value值
    如果列表元素在字典的key中,直接更新元素的value值,在原有的基礎上加1
"""
for item in s_li:
    if item not in word_dict:
        word_dict[item] = 1
    else:
        word_dict[item] += 1

print(word_dict)

結果:

                                 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章