Python 中的字典是Python中一個鍵值映射的數據結構
一,字典的基礎操作
1.1 創建字典
Python有兩種方法可以創建字典,第一種是使用花括號,另一種是使用內建 函數dict
>>> dict_A = {}
>>> dict_A = dict()
1.2 初始化字典
Python可以在創建字典的時候初始化字典
>>> dict_A = {"name" : 'cold'}
>>> dict_A = dict(name = 'cold') # 更優雅
很明顯第二種方法更加的優雅和減少一些特殊字符的輸入,但是有種情況第二種不能勝任
>>> key = 'name'
>>> dict_A = { key :'cold'} # {'name':'cold'}
>>> dict_A = dict(key = 'cold') # {'key': 'cold'}
明顯第二種方法就會引發一個不容易找到的bug
Python字典還有一種初始化方式,就是使用字典的fromkeys方法可以從列表中獲取元素作為鍵並用None或fromkeys方法的第二個參數初始化
>>> dict_A = {}.fromkeys(['name', 'blog'])
>>> dict_A
{'blog': None, 'name': None}
>>> dict_A = dict().fromkeys(['name', 'blog'])
>>> dict_A
{'blog': None, 'name': None}
>>> dict_A = dict().fromkeys(['name', 'blog'], 'linuxzen.com')
>>> dict_A
{'blog': 'linuxzen.com', 'name': 'linuxzen.com'}
1.3 優雅的獲取鍵值
字典可以這樣獲取到鍵的值
>>> dict_A = {'name':'cold', 'blog':'linuxzen.com'}
>>> dict_A['name']
'cold'
但是如果獲取不存在的鍵的值就會觸發的一個KeyError異常,字典有一個get方法,可以使用字典get方法更加優雅的獲取字典
>>> dict_A = dict(name= 'cold', blog='www.linuxzen.com')
>>> dict_A.get('name')
'cold'
>>> dict_A.get('blogname')
None
>>> dict_A.get('blogname', 'linuxzen')
'linuxzen'
我們看到使用get方法獲取不存在的鍵值的時候不會觸發異常,同時get方法接收兩個參數,當不存在該鍵的時候就會返回第二個參數的值 我們可以看到使用get更加的優雅
1.4 更新/添加
Python 字典可以使用鍵作為索引來訪問/更新/添加值
>>> dict_A = dict()
>>> dict_A['name'] = 'cold'
>>> dict_A['blog'] = 'linuxzen.com'
>>> dict_A
{'blog': 'linuxzen.com', 'name': 'cold'}
>>> dict_A
{'blog': 'linuxzen.com', 'name': 'cold night'}
同時Python字典的update方法也可以更新和添加字典
>>> dict_A = dict(name='cold', blog='linuxzen.com')
>>> dict_A.update({'name':'cold night', 'blogname':'linuxzen'})
>>> dict_A
{'blog': 'linuxzen.com', 'name': 'cold night', 'blogname': 'linuxzen'}
>>> dict_A.update(name='cold', blog='www.linuxzen.com') # 更優雅
>>> dict_A
{'blog': 'www.linuxzen.com', 'name': 'cold', 'blogname': 'linuxzen'}
Python字典的update方法可以使用一個字典來更新字典,也可以使用參數傳遞類似dict函數一樣的方式更新一個字典,上面代碼中哦功能的第二個更加優雅,但是同樣和dict函數類似,鍵是變量時也只取字面值
1.5 字典刪除
可以調用Python內置關鍵字del來刪除一個鍵值
>>> dict_A = dict(name='cold', blog='linuxzen.com')
>>> dict_A
{'blog': 'linuxzen.com', 'name': 'cold'}
>>> del dict_A['name']
>>> dict_A
{'blog': 'linuxzen.com'}
同時也可以使用字典的pop方法來取出一個鍵值,並刪除
>>> dict_A = dict(name='cold', blog='linuxzen.com')
>>> dict_A.pop('name')
'cold'
>>> dict_A
{'blog': 'linuxzen.com'}
1.6 獲取key,value
獲取所有key
>>> dict_A = dict(name='cold', blog='linuxzen.com')
>>> dict_A.keys()
['blog', 'name']
獲取key,value並循環
>>> dict_A = dict(name='cold', blog='linuxzen.com')
>>> for infokey, value in dict_A.items():
... print key, ':', value
...
blog : linuxzen.com
name : cold
1.7 字典鍵值互換
第一種,使用壓縮器:
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
m.items()
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
zip(m.values(), m.keys())
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
mi = dict(zip(m.values(), m.keys()))
mi
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
第二種,使用字典推導:
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
m
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
二,使用dict(zip(key,value))
1。
傳入映射對象做參數:dict(mapping,**kwargs)
1)傳入的參數mapping是映射對象。是位置參數。
2)如果鍵有重名,后者的值將替代前者值。
例如:
k = ['name', 'age', 'height']
v = ['齊德隆', '24', '187']
worker=zip(k,v)
d1 = dict(worker)
print(d1)
{'name': '齊德隆', 'age': '24', 'height': '187'}
2。
傳入可迭代的對象做參數:dict. (iterable,**kwargs)
1)參數 iterable 是可迭代的對象;是位置參數。
2)iterable的每個元素應是兩個子元素的可迭代對象,如:[( a , 1 ) , ( b , 2 )]
3)每個元素中的第一個子元素將成為字典的鍵,第二個子元素成為值。
4)如果鍵有重名,后者的值將替代前者的值。
例如(PS:這例子是個什么鬼?):
worker=[('name','齊德隆'),('age',24),('height',187)]
d1=dict(worker)
print(d1)
{'name': '齊德隆', 'age': 24, 'height': 187}
Dictionary Methods
METHODS | DESCRIPTION | 功能 |
---|---|---|
copy() | They copy() method returns a shallow copy of the dictionary. | 淺復制(指向同一內存地址) |
clear() | The clear() method removes all items from the dictionary. | 清除字典所有內容 |
pop() | Removes and returns an element from a dictionary having the given key. | 給定KEY刪除元素並返回 |
popitem() | Removes the arbitrary key-value pair from the dictionary and returns it as tuple. | 刪除鍵值對並返回該元組 |
get() | It is a conventional method to access a value for a key. | 按KEY查找VALUE |
dictionary_name.values() | returns a list of all the values available in a given dictionary. | 返回字典內所有VALUE |
str() | Produces a printable string representation of a dictionary. | 返回字符串形式的DICT(一個KEY-VALUE連一個那種) |
update() | Adds dictionary dict2’s key-values pairs to dict | 更新鍵值對 |
setdefault() | Set dict[key]=default if key is not already in dict | 與get()類似,但它新建不存在的鍵 |
keys() | Returns list of dictionary dict’s keys | 列舉所有KEY |
items() | Returns a list of dict’s (key, value) tuple pairs | 列舉所有KEY-VALUE,以元組形式 |
has_key() | Returns true if key in dictionary dict, false otherwise | 檢查DICT里是否有某KEY |
fromkeys() | Create a new dictionary with keys from seq and values set to value. | 用seq作KEY,對應同一個value |
type() | Returns the type of the passed variable. | 返回變量類型 |
cmp() | Compares elements of both dict. | 對比兩個字典 |