Python是一款簡單易懂的編程語言,具有開發效率高、表達能力強、應用廣泛等優點,是數據分析、人工智慧、Web開發等領域的首選語言之一。而Python字典(dict)作為Python內置類型之一,能夠高效地存儲和操作數據,是數據處理和數據分析的重要利器。
一、Python字典的基本操作
Python字典的基本操作包括創建字典、添加鍵值對、訪問鍵值對、刪除鍵值對、遍歷鍵值對等。
1、創建字典:
>>> dict1 = {'Name': 'Tom', 'Age': 18, 'Gender': 'Male'}
>>> dict2 = dict(Name='Tom', Age=18, Gender='Male')
除此之外,可以使用dict()函數從序列(列表、元組等)創建字典:
>>> dict3 = dict([('Name', 'Tom'), ('Age', 18), ('Gender', 'Male')])
2、添加鍵值對:
>>> dict1['Score'] = 90
3、訪問鍵值對:
>>> dict1['Name']
'Tom'
4、刪除鍵值對:
>>> del dict1['Score']
5、遍歷鍵值對:
>>> for key, value in dict1.items():
print(key, value)
二、Python字典的高級操作
Python字典的高級操作包括合併字典、嵌套字典、字典推導式等。
1、合併字典:
>>> dict1 = {'Name': 'Tom', 'Age': 18}
>>> dict2 = {'Gender': 'Male', 'Score': 90}
>>> dict1.update(dict2)
>>> print(dict1)
{'Name': 'Tom', 'Age': 18, 'Gender': 'Male', 'Score': 90}
2、嵌套字典:
>>> dict1 = {'Tom': {'Age': 18, 'Gender': 'Male'}, 'Jerry': {'Age': 20, 'Gender': 'Female'}}
>>> dict1['Tom']['Age']
18
3、字典推導式:
>>> dict1 = {'Tom': 18, 'Jerry': 20, 'Mick': 22}
>>> dict2 = {key: value for key, value in dict1.items() if value > 18}
>>> print(dict2)
{'Jerry': 20, 'Mick': 22}
三、Python字典的應用場景
Python字典具有高效地存儲和操作數據的特點,因此在數據處理和數據分析領域擁有廣泛的應用。
1、統計詞頻:
>>> text = 'Python is a popular programming language'
>>> word_count = {}
>>> for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
>>> print(word_count)
{'Python': 1, 'is': 1, 'a': 1, 'popular': 1, 'programming': 1, 'language': 1}
2、求解差集:
>>> set1 = {1, 2, 3, 4, 5}
>>> set2 = {3, 4, 5, 6, 7}
>>> diff = {'in set1': set1 - set2, 'in set2': set2 - set1}
>>> print(diff)
{'in set1': {1, 2}, 'in set2': {6, 7}}
3、統計成績:
>>> scores = {'Tom': 90, 'Jerry': 80, 'Mick': 70, 'John': 60, 'Lucy': 95}
>>> count = {}
>>> for score in scores.values():
if score in count:
count[score] += 1
else:
count[score] = 1
>>> print(count)
{90: 1, 80: 1, 70: 1, 60: 1, 95: 1}
四、總結
Python字典是Python內置類型之一,能夠高效地存儲和操作數據,具有合併字典、嵌套字典、字典推導式等高級操作。Python字典在數據處理和數據分析領域擁有廣泛的應用,包括統計詞頻、求解差集、統計成績等。掌握Python字典的使用,是數據處理和數據分析的基本技能之一。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/304232.html