Python3之字典(Dictionary)淺談

日期:2019年11月25日
作者:Commas
註釋:學習就是爲了忘記,讓我們來總結一下Python3字典的定義、11個元組方法的使用、遍歷的方法…

如果您想了解更多有關Python的知識,那麼請點【我】
《我的Python淺談系列目錄》



一、字典的定義

字典(Dictionary)和列表有些許類似,是有序的 (無序的)可變 的元素(鍵值對key:value)集合,每個值(value)都有一個唯一鍵(key)所對應,這個鍵就是對應值在字典的“索引”,即“字典[鍵名] = 值”。

RUNOOB.COM給出的字典定義:
字典是另一種可變容器模型,且可存儲任意類型對象。
字典的每個鍵值 key=>value 對用冒號 : 分割,每個鍵值對之間用逗號 , 分割,整個字典包括在花括號 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }

# (1)定義空字典
empty_dict = {}
# (2)定義一個鍵值對的字典
single_dict = {
    'abc': 'valueStr'
}
single_dict['abc'] # 值爲valueStr
# (3)定義多個鍵值對的字典
score_dict = {'Chinese': 99, 'Math': 100, 'English': 98}
score_dict['Chinese']  # 99
score_dict['Math']     # 100
score_dict['English']  # 98

在這裏插入圖片描述

二、字典的方法

獲取“字典方法”的方法如下:
Python語句:print(dir({}))
控制檯輸出:
[‘class’, ‘contains’, ‘delattr’, ‘delitem’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘getitem’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘iter’, ‘le’, ‘len’, ‘lt’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘setitem’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘items’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’]

  1. clear()
    D.clear() -> None. Remove all items from D.
    移除該字典的所有項(鍵值對),相當於清空字典
student_dict = {
    'Name': '小明',
    'Age': 18,
    'Class': 'First'
}
print(student_dict)
student_dict.clear()
print(student_dict)
# 控制檯輸出:
# {'Name': '小明', 'Age': 18, 'Class': 'First'}
# {}
  1. copy()
    D.copy() -> a shallow copy of D
    字典的淺複製,重新開闢內存空間
student_dict = {'name': '小明'}
print('淺複製結果:')
#(1)淺複製
copy_student_dict = student_dict.copy()
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(copy_student_dict),
    copy_student_dict
))
copy_student_dict['name'] = "Commas"
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(copy_student_dict),
    copy_student_dict
))
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(student_dict),
    student_dict
))
print('深複製結果:')
# (2)深複製
equal_student_dict = student_dict
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(equal_student_dict),
    equal_student_dict
))
equal_student_dict['name'] = "Commas"
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(equal_student_dict),
    equal_student_dict
))
print('{0}的內存地址爲:{1},其內容爲{2}'.format(
    'copy_student_dict',
    id(student_dict),
    student_dict
))

(i)知識加油站:
① id(object)–> 獲得 obj 的內存地址(10進制)
② 如果想比較系統的瞭解Python字符串格式化,請看《Python3之字符串格式化淺談》
(ii)控制檯輸出:
淺複製結果:
copy_student_dict的內存地址爲:1962127493592,其內容爲{‘name’: ‘小明’}
copy_student_dict的內存地址爲:1962127493592,其內容爲{‘name’: ‘Commas’}
copy_student_dict的內存地址爲:1962128181144,其內容爲{‘name’: ‘小明’}
深複製結果:
copy_student_dict的內存地址爲:1962128181144,其內容爲{‘name’: ‘小明’}
copy_student_dict的內存地址爲:1962128181144,其內容爲{‘name’: ‘Commas’}
copy_student_dict的內存地址爲:1962128181144,其內容爲{‘name’: ‘Commas’}

名稱 操作 原字典id值 複製字典id值 說明
淺複製 copy() 1962128181144 1962127493592 不共享內存,所以修改一個字典的值,另外一個字典的值不會修改
深複製 = 1962128181144 1962128181144 共享內存(實質上是兩個不同的標識符指向了同一個內存地址),所以修改一個字典的值,另外一個字典的值也會修改
  1. fromkeys(seq[,value])
    Create a new dictionary with keys from iterable and values set to value.
    創建一個新字典,以序列 seq 中元素做字典的鍵,val 爲字典所有鍵對應的初始值
# name_tuple、name_list均是序列數據結構
name_tuple = ("星爺", "達叔", "Commas")
name_list = ["星爺", "達叔", "Commas"]
# (1)fromkeys(seq)
new_dict = dict.fromkeys(name_tuple)
print(new_dict)
# (2)fromkeys(seq,value)
new_dict.clear() # 清空字典
new_dict = dict.fromkeys(name_list, 100)
print(new_dict)
# 控制檯輸出:
# {'星爺': None, '達叔': None, 'Commas': None}
# {'星爺': 100, '達叔': 100, 'Commas': 100}

知識加油站:
Python3中有6個序列的內置類型,分別爲列表、元組、字符串、Unicode字符串、buffer對象、range對象(Python2的是xrange對象)。

  1. get(key[,default])
    Return the value for key if key is in the dictionary, else default.
    返回指定鍵的值,如果值不在字典中返回default值
score_dict = {'語文': 98, '英語': 99}
print('{}得了{}分'.format('語文', score_dict.get('語文'), 100))
print('{}得了{}分'.format('英語', score_dict.get('英語')))
print('{}得了{}分'.format('數學', score_dict.get('數學', 100)))
print('{}得了{}分'.format('物理', score_dict.get('物理')))
print('字典現在爲{}'.format(score_dict))
# 控制檯輸出:
# 語文得了98分
# 英語得了99分
# 數學得了100分
# 物理得了None分
# 字典現在爲{'語文': 98, '英語': 99}
  1. setdefault(key[,default])
    Insert key with a value of default if key is not in the dictionary.
    Return the value for key if key is in the dictionary, else default.
    返回指定鍵的值,如果值不在字典中返回default值,並且將此鍵值更新到原字典。
score_dict = {'語文': 98, '英語': 99}
print('{}得了{}分'.format('語文', score_dict.setdefault('語文'), 100))
print('{}得了{}分'.format('英語', score_dict.setdefault('英語')))
print('{}得了{}分'.format('數學', score_dict.setdefault('數學', 100)))
print('{}得了{}分'.format('物理', score_dict.setdefault('物理')))
print('字典現在爲{}'.format(score_dict))
# 控制檯輸出:
# 語文得了98分
# 英語得了99分
# 數學得了100分
# 物理得了None分
# 字典現在爲{'語文': 98, '英語': 99, '數學': 100, '物理': None}
  1. pop(key[,default])
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised
    返回指定鍵的值,並且刪除該鍵,如果值不在字典中,那麼:
    1、有default值,則返回default值;
    2、無default值,則拋出KeyError異常。
score_dict = {'Math': 100, 'English': 97}
print('{}得了{}分'.format('Math', score_dict.pop('Math')))
print('{}得了{}分'.format('Physics', score_dict.pop('Physics', 100)))
print('字典現在爲{}'.format(score_dict))

# 下面這一句會拋出KeyError異常
# print('{}得了{}分'.format('Chemistry', score_dict.pop('Chemistry')))

# 控制檯輸出:
# Math得了100分
# Physics得了100分
# 字典現在爲{'English': 97}
  1. popitem()
    D.popitem() -> (k, v), remove and return some (key, value) pair as a
    2-tuple; but raise KeyError if D is empty.
    移除最後一個鍵值對,並且以元組形式返回被移除的鍵值對;若字典爲空,則會拋出KeyError異常。
score_dict = {'Math': 100, 'English': 97}
popitem_tuple = score_dict.popitem()
print("移除並返回的元組:{}".format(popitem_tuple))
print('字典現在爲{}'.format(score_dict))
# 控制檯輸出:
# 移除並返回一個元組:('English', 97)
# 字典現在爲{'Math': 100}
  1. update(dict)
    D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]
    把字典dict的鍵值對全部更新到原字典(調用該方法的字典)中,
    如果鍵不存在,就追加鍵值對到原字典;
    如果鍵存在,就更新原字典該鍵的值。
score_dict = {'語文': 98, '數學': 100}
new_dict = {'英語': 99, '數學': 88}
print('原字典:%s' % new_dict)
new_dict.update(score_dict)
print('新字典:%s' % new_dict)
# 控制檯輸出:
# 原字典:{'英語': 99, '數學': 88}
# 新字典:{'英語': 99, '數學': 100, '語文': 98}
  1. items()、keys()、values()

這三個方法有些特殊,至於爲什麼特殊?主要體現在方法的返回值上,詳情如下表:

方法 數據類型 返回值 說明
items() <class ‘dict_items’> a set-like object 可迭代的,長得像集合的對象
keys() <class ‘dict_keys’> a set-like object 可迭代的,長得像集合的對象
values() <class ‘dict_values’> an object 可迭代的對象

D.items() -> a set-like object providing a view on D’s items
D.keys() -> a set-like object providing a view on D’s keys
D.values() -> an object providing a view on D’s values

(1)看一看方法的返回值是什麼?

score_dict = {'語文': 97, '數學': 100, '英語': 99}
items_dict = score_dict.items()
keys_dict = score_dict.keys()
values_dict = score_dict.values()

temp_str = '數據類型是{},數據爲 {}'
print_items = temp_str.format(type(items_dict), items_dict)
print_keys = temp_str.format(type(keys_dict), keys_dict)
print_values = temp_str.format(type(values_dict), values_dict)

print(print_items)
print(print_keys)
print(print_values)
# 控制檯輸出:
# 數據類型是<class 'dict_items'>,數據爲 dict_items([('語文', 97), ('數學', 100), ('英語', 99)])
# 數據類型是<class 'dict_keys'>,數據爲 dict_keys(['語文', '數學', '英語'])
# 數據類型是<class 'dict_values'>,數據爲 dict_values([97, 100, 99])

(2)瞧一瞧返回值(對象)有哪些方法?

score_dict = {'語文': 97, '數學': 100, '英語': 99}

items_dict = score_dict.items()
keys_dict = score_dict.keys()
values_dict = score_dict.values()

print(dir(items_dict))
print(dir(keys_dict))
print(dir(values_dict))
# 控制檯輸出:
# ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'isdisjoint']
# ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'isdisjoint']
# ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

(i)從控制檯輸出的結果中可以看出:
1、三個對象的方法中都有__ iter __方法,所以三個對象均可以迭代;
2、三個對象中,只有前兩個對象均有一個相同的公有方法isdisjoint(),這個方法是集合所特有的方法,但是這兩個對象又不是集合,所以稱這兩個對象是長得像集合的對象。
(ii)知識加油站
isdisjoint():判斷兩個集合是否包含相同的元素,如果沒有返回 True,否則返回 False。【點擊這裏可以瞭解詳細使用】

(3)測一測返回值(對象)可否用索引?

score_dict = {'Chinese': 97, 'Math': 100, 'English': 99}
items_dict = score_dict.items()
keys_dict = score_dict.keys()
values_dict = score_dict.values()

try:
    print(items_dict[0])
except Exception as e:
    print(e)

try:
    print(keys_dict[0])
except Exception as e:
    print(e)

try:
    print(values_dict[0])
except Exception as e:
    print(e)

# 控制檯輸出:
# 'dict_items' object does not support indexing
# 'dict_keys' object does not support indexing
# 'dict_values' object does not support indexing

(i)知識加油站:
上面代碼用到了異常捕獲的知識,詳細教程可以看我寫的另外一篇原創博客《Python3之錯誤和異常淺談》
(ii)小結:
控制檯輸出的結果均是不支持索引(index),所以Python並不像其他語言一樣,得到的是列表對象,而是一種特殊的對象。

(4)試一試遍歷這三個返回值(對象)

score_dict = {'語文': 97, '數學': 100, '英語': 99}

#(1)遍歷items()--->元組
items_dict = score_dict.items()
temp_str = '元組值爲{},其元素分別爲{}、{}'
for item in items_dict:
    print_str = temp_str.format(item, item[0], item[1])
    print(print_str)
# 控制檯輸出:
# 元組值爲('語文', 97),其元素分別爲語文、97
# 元組值爲('數學', 100),其元素分別爲數學、100
# 元組值爲('英語', 99),其元素分別爲英語、99

#(1)遍歷items()--->key:value
temp_str = 'key值爲{},value值爲{}'
for k, v in items_dict:
    print_str = temp_str.format(k, v)
    print(print_str)
# 控制檯輸出:
# key值爲語文,value值爲97
# key值爲數學,value值爲100
# key值爲英語,value值爲99

#(2)遍歷keys()
keys_dict = score_dict.keys()
temp_str = 'key值爲{}'
for key in keys_dict:
    print_str = temp_str.format(key)
    print(print_str)
# 控制檯輸出:
# key值爲語文
# key值爲數學
# key值爲英語

#(3)遍歷values()
values_dict = score_dict.values()
temp_str = 'value值爲{}'
for value in values_dict:
    print_str = temp_str.format(value)
    print(print_str)
# 控制檯輸出:
# value值爲97
# value值爲100
# value值爲99

三、字典的遍歷

需要指出的是,字典的遍歷,返回的是鍵值,並不能返回鍵值對,如需返回鍵值對,可以參考字典的item()方法,請看上文,有所介紹。

  1. 正確遍歷字典的示例
score_dict = {'語文': 97, '數學': 100, '英語': 99}
for key in score_dict:
    print(key, score_dict.get(key))
# 控制檯輸出:
# 語文 97
# 數學 100
# 英語 99
  1. 錯誤遍歷字典的示例
score_dict = {'語文': 99, '數學': 100, '英語': 98}
temp_str = 'key值爲“{}”,value值爲“{}”'
for key, value in score_dict:
    print(temp_str.format(key, value))
# 控制檯輸出:
# key值爲“語”,value值爲“文”
# key值爲“數”,value值爲“學”
# key值爲“英”,value值爲“語” 

本文參考:
1、https://www.runoob.com/python/python-dictionary.html


版權聲明:本文爲博主原創文章,如需轉載,請給出:
原文鏈接:https://blog.csdn.net/qq_35844043/article/details/103235952

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