Python內置四大數據結構之字典的介紹及實踐案例

                                                                              Python字典的介紹及實踐案例

一、字典(Dict)介紹

       字典是Python內置的四大數據結構之一,是一種可變的容器模型,該容器中存放的對象是一系列以(key:value)構成的鍵值對。其中鍵值對的key是唯一的,不可重複,且一旦定義不可修改;value可以是任意類型的數據,可以修改。通過給定的key,可以快速的獲取到value,並且這種訪問速度和字典的鍵值對的數量無關。字典這種數據結構的設計還與json的設計有異曲同工之妙。
       格式如下所示:

  d = {key1 : value1, key2 : value2 }

二、使用示例

       2.1. 字典的創建:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

print(d)   # {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'海角', '天涯'}, ('male', 'female'): 'male'}

      注意事項:Dict的key必須要是可被hash的,在python中,可被hash的元素有:int、float、str、tuple;不可被hash的元素有:list、set、dict。如下所示:

      2.2. 字典的訪問:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

# 根據鍵獲取值
print(d['name'])  # IT之旅
print(d.get('name'))  # IT之旅

# 成員存在則進行訪問
if 'age' in d:
    print(d.get('age'))  # 25

# 循環遍歷訪問
for k in d:
    print(k, d[k])
'''
name IT之旅
age 25
hobby ['編程', '看報', 111]
location {'天涯', '海角'}
('male', 'female') male
'''
for k, v in d.items():
    print(k, '-->', v)
'''
name --> IT之旅
age --> 25
hobby --> ['編程', '看報', 111]
location --> {'海角', '天涯'}
('male', 'female') --> male
'''
for v in d.values():
    print(v)
'''
IT之旅
25
['編程', '看報', 111]
{'海角', '天涯'}
male
'''

      2.2. 修改字典的值:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

print(d['age'])  # 25

d['age'] = 27
print(d['age'])  # 27

      2.3. 刪除字典的元素:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

del d['name']
print(d)  # name鍵值對已被刪除

d.clear()
print(d)  # d已被清除,輸出爲空的對象 {}
del d
print(d)  # name 'd' is not defined

      2.4. 增加字典元素:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

del d['name']
del d['hobby']
del d['location']
print(d)  # {'age': 25, ('male', 'female'): 'male'}

d.update({'name_1': '測試用戶名'})  # 添加元素值
print(d)  # {'age': 25, ('male', 'female'): 'male', 'name_1': '測試用戶名'}

m = {'test': 'test', 1: 1}  # 合併字典值
d.update(m)
print(d)  # {'age': 25, ('male', 'female'): 'male', 'name_1': '測試用戶名', 'test': 'test', 1: 1}

     2.5. 字典的複製:

d = {'name': 'IT之旅', 'age': 25, 'hobby': ['編程', '看報', 111], 'location': {'天涯', '海角'}, ('male', 'female'): 'male'}

m = d.copy()  # 淺複製
print(m == d)  # True
print(id(m) == id(d))  # False

n = d  # 直接賦值
print(id(n) == id(d))  # True

'''
需要注意直接賦值和淺拷貝的區別
'''

     2.6.  python內置了一些函數用於操作字典,包含有:計算字典元素個數的len()函數,以可打印字符串輸出的str()函數,刪除字典給定鍵 key 所對應值的pop()函數,等等。

三、實踐案例 - 統計英文文章中單詞出現的頻率

       英文句子如下:

With the gradual deepening of Internet of things, artificial intelligence, big data and other concepts, the construction of smart city is particularly urgent, and smart transportation is an important step in this link, which is not only the key words of urban construction,
It is also an important traffic information data of each city component. In order to strengthen data information sharing and exchange, each region has begun to make efforts to build.
As an important indicator of road section, traffic indicator cone plays an important role in road section status indication and vehicle drainage.
The traditional cone barrel has some disadvantages, such as single function, poor warning effect, inconvenient transportation and poor ability to withstand harsh conditions, which can not meet the requirements of current conditions. Based on this situation,
We start to use NB-IoT communication technology and IPv6 protocol to further explore the use value of cone barrel and further improve the utilization rate.
What is the next direction of the Internet of things? We'll see

    代碼如下:(將上面的單詞放進一個文本中,然後修改代碼中文本文件的位置即可運行代碼)

original_words = open(r'C:\Users\itour\Desktop\words-original.txt', 'r', encoding='utf-8')
# 將文本中的句子分割成一個一個單次,去除標點符號後存入word_list列表中。
word_list = []
for lines in original_words:
    word = lines.replace('\n', '').split(' ')
    for reduce_word in word:  # 去除單次中的標點符號
        
        word_list.append(reduce_word.strip(',').strip('?').strip('.'))

# 使用字典數據結構統計單詞出現的頻率
word_dict = {}
for w in word_list:
    if w in word_dict.keys():
        word_dict[w] += 1
    else:
        word_dict[w] = 1
# 輸出結果
print(word_dict)

'''
{'With': 1, 'the': 8, 'gradual': 1, 'deepening': 1, 'of': 10, 'Internet': 2, 
'things': 2, 'artificial': 1, 'intelligence': 1, 'big': 1, 'data': 3, 'and': 7,
 'other': 1, 'concepts': 1, 'construction': 2, 'smart': 2, 'city': 2, 'is': 5, 
 'particularly': 1, 'urgent': 1, 'transportation': 2, 'an': 4, 'important': 4, 
 'step': 1, 'in': 2, 'this': 2, 'link': 1, 'which': 2, 'not': 2, 'only': 1, 'key': 1, 
 'words': 1, 'urban': 1, 'It': 1, 'also': 1, 'traffic': 2, 'information': 2, 'each': 2, 
 'component': 1, 'In': 1, 'order': 1, 'to': 6, 'strengthen': 1, 'sharing': 1, 'exchange': 1,
  'region': 1, 'has': 2, 'begun': 1, 'make': 1, 'efforts': 1, 'build': 1, 'As': 1, 
  'indicator': 2, 'road': 2, 'section': 2, 'cone': 3, 'plays': 1, 'role': 1, 
  'status': 1, 'indication': 1, 'explore': 1}

'''

四、總結

       Python的字典數據結構,在很多方面都有應用,因此,掌握這個數據結構是非常必要的。

發佈了62 篇原創文章 · 獲贊 171 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章