Python3 數據類型-字典

字典是一種可變數據類型,且可存儲任意類型對象。python

字典使用大括號"{}"括起來,由鍵(key)和值(values)組成,鍵只能使用不可變類型定義,值能夠使用可變類型{'鍵':'值'}數組

一 建立

實例(Python3.0+):

dic = {'name':'makes','age':'30','hobby':'gril','is_handsome':True}
print(dic['name'])     #makes

dic1 = {1:'makes','hobby':{'age':35,'gril_name':'wanglk'},'age':30}
print(dic1['hobby'])    #{'gril_name': 'wanglk', 'age': 35}

dic2 = dict((('name','makes'),('age',30)))
print(dic2)      #{'name': 'makes', 'age': 30} 

二 修改

實例(Python3.0+):直接修改

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8;            # 更新 Age
dict['School'] = "清華大學"  # 添加信息

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

dict.setdefault

  • 鍵存在,不改動,返回字典中相應的值
  • 鍵不存在,在字典中添加相應的鍵值對,並返回相應的值

實例(Python3.0+):

dic = {'name':'makes','age':'30','hobby':'gril','is_handsome':True}

#鍵存在,不改動,返回字典中相應的值
dic.setdefault('age',35)
ret = dic.setdefault('age',35)  #有返回值
print(ret)
#30
print(dic)
#{'name': 'makes', 'age': '30', 'is_handsome': True, 'hobby': 'gril'}

#鍵不存在,在字典中添加相應的鍵值對,並返回相應的值
dic.setdefault('salary',10000)
ret = dic.setdefault('salary','10000')
print(dic)
#{'name': 'makes', 'hobby': 'gril', 'salary': 10000, 'age': '30', 'is_handsome': True}
print(ret)
#10000

三 查

dict.keys()

  • 以列表的方式返回字典中的全部鍵(keys)

實例(Python3.0+):

dic1 = {'age':19,'name':'lvcm','hobby':'study'}
print(dic1['age'])  #19

print(dic1.keys()) 
#查看字典中的全部鍵,dict_keys(['age', 'hobby', 'name'])
print(type(dic1.keys()))
#<class 'dict_keys'>
print(list(dic1.keys()))
#['name', 'age', 'hobby']

dic2 = {'name':'makes','age':['123','345'],'salary':20000}
print('age的值爲:',dic2['age'][1])
#字典中的值爲列表時,能夠使用dic.[keys][索引]方式查看
#age的值爲: 345  

dict.values()

  • 以列表的方式返回字典中的全部值(values)

實例(Python3.0+):

dic1 = {'age':19,'name':'makes','hobby':'study'}

print(dic1.values())
#dict_values(['makes', 19, 'study'])
print(list(dic1.values()))
#['study', 19, 'makes']

四 更新

dict.update(dict1)

  • 把字典dict1的鍵/值對更新到dict裏
  • 當兩個字典中的鍵不一樣時,把dict1的鍵值插入到dict中
  • 當兩個字典中存在相同鍵時,dict1覆蓋dict的鍵值

實例(Python3.0+):

# 當兩個字典徹底不相同時
dic1 = {'name':'lvcm','age':19}
dic2 = {'hobby':'girl','salary':10000}

dic1.update(dic2)

print(dic1)
# dic1--> {'hobby': 'girl', 'age': 19, 'salary': 10000, 'name': 'lvcm'}
print(dic2)
# dic2 --> {'hobby': 'girl', 'salary': 10000}

# 當兩個字典存在相同鍵時,會覆蓋前面的鍵值
dic1 = {'name':'lvcm','age':19}
dic2 = {'hobby':'girl','salary':10000,'name':'1111'}

dic1.update(dic2)
# dic1 --> {'salary': 10000, 'age': 19, 'hobby': 'girl', 'name': '1111'}
print(dic1)
# dic2 --> {'salary': 10000, 'hobby': 'girl', 'name': '1111'}
print(dic2)  

五 刪除

del dict[keys]

  • 刪除字典中的某個鍵值對
  • 沒有返回值

實例(Python3.0+):

dic1 = {"name":"makes","age":19,"salary":10000}

del dic1["name"]
print(dic1)

del dict

  • 刪除整個字典

實例(Python3.0+):

dic1 = {"name":"makes","age":19,"salary":10000}

del dic1
print(dic1)
#NameError: name 'dic1' is not defined(字典已刪除,因此報錯dict1未定義) 

dict.clear()

  • 清空字典

實例(Python3.0+):

dic1 = {"name":"makes","age":19,"salary":10000}

dic.clear()
print(dic1) 
# {} 

dict.popitem()

  • 隨機刪除字典中的一組鍵值對  
  • 有返回值,以元祖方式返回
  • 應用不普遍

實例(Python3.0+):

dict1 = {"name":"makes","age":19,"salary":10000}

dict2 = dict1.popitem()
print(dict1)
#{'age': 19, 'salary': 10000}
print(dict2)
#('name', 'makes')

六 字典排序

sorted()

實例(Python3.0+):

dic6 = {2:111,3:222,4:333}

# 以鍵來進行排序
print(sorted(dic6.items()))
# 以值進行排序
print(sorted(dic6.values()))  

七 遍歷

實例(Python3.0+):

dic7 = {'name':'makes','age':19}

print('dic7 items:',dic7.items())
#以列表返回可遍歷的(鍵, 值) 元組數組
#dic7 items: dict_items([('name', 'lvcm'), ('age', 19)])

for key in dic7:
    print(key)

"""
針對鍵進行遍歷,也可以下寫法:
for key in dic7.keys():
    print(key)
name
age
"""

for values in dic7.values():
    print(values)
"""
針對值進行遍歷
19
lvcm
"""

for i in dic7:
    print(i,dic7[i])
"""
針對鍵和值組合遍歷,推薦使用
name makes
age 19
"""

for i,v in dic7.items():
    print(i,v)
"""
針對鍵和值組合遍歷
age 19
name makes
"""

八 其它操做及方法

dict.fromkeys()

  • 初始化字典時使用

實例1(Python3.0+):

dic5 = dict.fromkeys(['host1','host2','host3'],'test')
print(dic5) # {'host2': 'test', 'host1': 'test', 'host3': 'test'}

dic5 = dict.fromkeys(['host1','host2','host3'],['test','test1'])
print(dic5)
#{'host3': ['test', 'test1'], 'host2': ['test', 'test1'], 'host1': ['test', 'test1']}

實例2(Python3.0+):

dic5 = dict.fromkeys(['host1','host2','host3'],['test','test1'])

dic5['host1'][1]='test3'
print(dic5)
# {'host1': ['test', 'test3'], 'host3': ['test', 'test3'], 'host2': ['test', 'test3']}
# 想法是把host1中的test1修改爲test3,可是結果卻修改了所有,此法慎用

字典嵌套

實例(Python3.0+):

dic1 = {
    '歐美':{
    'www.baidu.com':['免費的','質量通常']},
    '日韓':{
    'www.runoob.com':['收費的','質量標清']},
    '國產':{
    'www.sina.com.cn':['免費的','高清']},
    '三級片':{
    'www.1024.com':['免費的','下載速度慢']},
    '四級片':{
    'www.bokeyuan.com':['收費的','無碼']},
    }
print(dic1)
#{'歐美': {'www.baidu.com': ['免費的', '質量通常']}, '國產': {'www.sina.com.cn': ['免費的', '高清']}, '日韓': {'www.runoob.com': ['收費的', '質量標清']}, '三級片': {'www.1024.com': ['免費的', '下載速度慢']}, '四級片': {'www.bokeyuan.com': ['收費的', '無碼']}}

九 函數

len()

  • 計算字典元素個數,即鍵的總數。

實例(Python3.0+):

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print(len(dict))
#3

type(variable)

  • 返回輸入的變量類型,若是變量是字典就返回字典類型

實例(Python3.0+):

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print(type(dict))
#<class 'dict'>

str(dict)

  • 輸出字典,以可打印的字符串表示

實例(Python3.0+):

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print(str(dict))
#"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}" 
相關文章
相關標籤/搜索