近幾年,人工智能等領(lǐng)域已然成為當(dāng)前的就業(yè)熱門賽道,對(duì)于那些胸懷壯志、渴望在就業(yè)市場(chǎng)中脫穎而出的莘莘學(xué)子們來說,除了緊密關(guān)注這些熱門行業(yè)和高端崗位,還需參加Python編程工程師培訓(xùn)課程學(xué)習(xí)Python編程技術(shù),持續(xù)提升自己的專業(yè)技能,作為人工智能核心技術(shù)的Python編程語言,我們要了解起最基本原理,今天八維職業(yè)學(xué)校和大家一起來看看Python編程語言中怎么使用字典?希望對(duì)想要學(xué)習(xí)和了解python編程工程師這個(gè)行業(yè)的同學(xué)有所幫助。
Python字典是一種可變?nèi)萜髂P停梢源鎯?chǔ)任意類型的對(duì)象。字典中的每個(gè)元素都是由一個(gè)鍵和一個(gè)值組成,鍵和值之間用冒號(hào)隔開,每個(gè)鍵值對(duì)之間用逗號(hào)隔開,整個(gè)字典用花括號(hào){}包裹。Python字典操作方法包括字典的創(chuàng)建、訪問、添加、刪除、修改等操作。
1. 字典的創(chuàng)建
Python字典的創(chuàng)建可以通過直接賦值、dict()函數(shù)、{key:value}等方式進(jìn)行。例如:
直接賦值創(chuàng)建字典
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
print(dict1)
使用dict()函數(shù)創(chuàng)建字典
dict2 = dict(name='Jerry', age=20, gender='female')
print(dict2)
使用{key:value}創(chuàng)建字典
dict3 = {'name': 'Lucy', 'age': 22, 'gender': 'female'}
print(dict3)
2. 字典的訪問
Python字典的訪問可以通過鍵來獲取對(duì)應(yīng)的值,如果鍵不存在則會(huì)拋出KeyError異常。例如:
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
獲取鍵為'name'的值
name = dict1['name']
print(name)
獲取鍵為'height'的值,會(huì)拋出KeyError異常
height = dict1['height']
print(height)
如果不確定鍵是否存在,可以使用get()方法,如果鍵不存在則返回None或指定的默認(rèn)值。例如:
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
獲取鍵為'name'的值
name = dict1.get('name')
print(name)
獲取鍵為'height'的值,返回None
height = dict1.get('height')
print(height)
獲取鍵為'height'的值,返回指定的默認(rèn)值
height = dict1.get('height', 180)
print(height)
3. 字典的添加和修改
Python字典的添加和修改可以通過直接賦值或update()方法進(jìn)行。例如:
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
添加鍵值對(duì)
dict1['height'] = 180
print(dict1)
修改鍵值對(duì)
dict1['age'] = 20
print(dict1)
使用update()方法添加鍵值對(duì)
dict1.update({'weight': 70})
print(dict1)
使用update()方法修改鍵值對(duì)
dict1.update({'age': 22})
print(dict1)
4. 字典的刪除
Python字典的刪除可以通過del關(guān)鍵字或pop()方法進(jìn)行。例如:
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
刪除鍵為'age'的鍵值對(duì)
del dict1['age']
print(dict1)
刪除不存在的鍵會(huì)拋出KeyError異常
del dict1['height']
使用pop()方法刪除鍵值對(duì)
dict1.pop('gender')
print(dict1)
使用pop()方法刪除不存在的鍵會(huì)返回指定的默認(rèn)值
gender = dict1.pop('gender', 'unknown')
print(gender)
5、字典的遍歷
Python字典的遍歷可以通過for循環(huán)遍歷鍵或鍵值對(duì),也可以通過keys()、values()、items()方法獲取字典的鍵、值、鍵值對(duì)。例如:
dict1 = {'name': 'Tom', 'age': 18, 'gender': 'male'}
遍歷鍵
for key in dict1:
print(key)
遍歷值
for value in dict1.values():
print(value)
遍歷鍵值對(duì)
for key, value in dict1.items():
print(key, value)
獲取鍵列表
keys = list(dict1.keys())
print(keys)
獲取值列表
values = list(dict1.values())
print(values)
獲取鍵值對(duì)列表
items = list(dict1.items())
print(items)
自媒體就業(yè)前景分析
在當(dāng)今數(shù)字化時(shí)代,自媒體的蓬勃發(fā)展為眾多求職者帶來了新的機(jī)遇和挑戰(zhàn)。以下是對(duì)自媒體就業(yè)前景的詳細(xì)分析。