Python學習之路-----字典操作

字典

字典是一種可變容器類型,且可存儲任意類型對象

字典的沒個鍵值對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中,格式如下:

dict = {key1 : value, key2 : value2,.....}

鍵必須是唯一的,但值則不必

值可以取任意數據類型,但是鍵只能取不變數據類型(元組、字符串、數字)

創建字典

my_dict = {'name' : 'YWH', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

訪問字典裏的值

把需要訪問的值的相應的鍵放入方括號[ ]中

#如果對字典裏沒有的鍵進行訪問,則會輸出錯誤如下:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'
my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}
print('My name is %s:'%my_dict['name'])
print('My year is %d:'%my_dict['year'])
if my_dict['gender'] == 1:
	print("I am a Boy!")
else
	print('I am a Girl!')
	
'''
My name is Yuwenhao
My year is 21
I am a Boy!
'''

修改字典

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}
print('My year is %d:'%my_dict['year'])

my_dict['year'] = 22
my_dict['School'] = 'HZAU'
print('Now, My year is %d:'%my_dict['year'])
print('My school is %s:'%my_dict['School'])

'''
My year is 21:
Now, My year is 22:
My school is HZAU:
'''

刪除字典

能刪除單一的元素也能清空字典

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

del my_dict['name']
my_dict.clear()   #清空一個字典
print(my_dict)

del my_dict
print(my_dict)    #刪除一個字典

'''
{}    
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 8, in <module>
    print(my_dict)
NameError: name 'my_dict' is not defined
'''

字典的鍵

1)字典不允許同一個鍵出現兩次。創建時如果痛一個鍵被賦值兩次,後一個值將會被記住

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169],'name':'YWH'}

print("my name is",my_dict['name'])
print("my dist is",my_dict)
'''
my name is YWH
my dist is {'name': 'YWH', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''

2)鍵必須是不可變數據類型

error_dist = {['name'] : 'Ywh'}
print("my name is",error_dist['name'])

'''
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 1, in <module>
    error_dist = {['name'] : 'Ywh'}
TypeError: unhashable type: 'list'
'''

字典內置函數

len(dict) 計算字典元素的個數(鍵的個數)

str(dict) 輸出字典,以可打印的字符串表示

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

str(my_dict)

'''
"{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}"
'''

字典的方法

dict.clear() 刪除字典內所有元素

dict.copy() 返回字典的一個淺複製

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

copy_dict = {}
copy_dict = my_dict.copy()

print(copy_dict)

'''
{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''

dict.fromkeys(seq, value) 創建一個新字典,以序列seq中的元素作爲字典的鍵,value作爲字典所有鍵對應的初始值,默認爲None

my_dict = {}
seq = ('name','year','gender')
my_dict = my_dict.fromkeys(seq)
print(my_dict)
my_dict = my_dict.fromkeys(seq,100)
print(my_dict)

'''
{'name': None, 'year': None, 'gender': None}
{'name': 100, 'year': 100, 'gender': 100}
'''

key in dict 如果鍵在字典裏返回True

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Henan','Zhengzhou','Erqi','Xinghuajie',169]}

print('name' in my_dict)
print('color' in my_dict)

'''
True
False
'''

dict.items() 以列表返回可便利的(鍵、值)元組數組

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

list = my_dict.items()

print(list)

'''
dict_items([('name', 'Yuwenhao'), ('year', 21), ('gender', 1), ('address', ['Xinghuajie', 169])])
'''

dict.keys() 返回一個迭代器,可以使用list()來轉換爲列表

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
iterator = my_dict.keys()
print(iterator)
iterator_list = list(my_dict.keys())
print(iterator_list)

'''
dict_keys(['name', 'year', 'gender'])
['name', 'year', 'gender']
'''

dict.setdefault(key,default=None) 和get()類似,但如果鍵不存在於字典中,將會添加鍵並將值設爲default

dict.update(dict2) 把dict2中的鍵值對更新到dict中去

dict.values() 返回一個迭代器,可以使用list()來轉換爲列表

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
iterator = my_dict.values()
print(iterator)
iterator_list = list(my_dict.values())
print(iterator_list)

'''
dict_values(['Yuwenhao', 21, 1])
['Yuwenhao', 21, 1]
'''

dist.pop(key,default) 刪除字典給的鍵key所對應的值,返回值爲被刪除的值。key值必須給出!!不然會報錯。如果要刪除的 key 不存在,則需要添加默認值,否則會報錯:

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
print(my_dict.pop('name'))
print(my_dict.pop('color','None'))

'''
Yuwenhao
None
'''

dict.popitem() 隨機返回並刪除字典中的最後一對鍵和值

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