自學Python2.4-基本數據類型-字典dict(objct)

Python dict方法總結 

1、字典介紹python

1.字典概述數組

①字典是python中惟一內建的映射類型。又稱關聯數組或散列
②映射類型對象裏哈希值(鍵,key)和指向的對象(值,value)是一對多的的關係,一般被認爲是可變的哈希表
③字典對象是可變的,它是一個容器類型,能存儲任意個數的Python對象,其中也可包括其餘容器類型。
④字典經過鍵實現元素存取,可變類型容器,長度可變,異構,嵌套app

2.字典類型與序列類型的區別:ide

①存取和訪問數據的方式不一樣。
②序列類型只用數字類型的鍵(從序列的開始按數值順序索引);
③映射類型能夠用其餘對象類型做鍵(如:數字、字符串、元祖,通常用字符串做鍵),和序列類型的鍵不一樣,映射類型的鍵直接或間接地和存儲數據值相關聯。
④映射類型中的數據是無序排列的。這和序列類型是不同的,序列類型是以數值序排列的。
⑤映射類型用鍵直接「映射」到值。函數

2、字典的基本操做post

一、建立字典this

   {key1:value1,key2:value2, .....}url

   {}   表示空字典spa

   {‘x’:32,‘y’:[1,2,3]}rest

特色:
一、鍵與值用冒號「:」分開;
二、項與項用逗號「,」分開;
三、字典中的鍵必須是惟一的,而值能夠不惟一。

建議:

若是字典中的值爲數字,最好使用字符串數字形式,如:'age':'26′ 而不用 ‘age':26

二、如何訪問字典中的值?
     dict[key] 形式返回鍵key對應的值value,若是key不在字典中會引起一個KeyError。

dict={'x':32,'y':[1,2,3,4,]}
result=dict['x']   #取值的時候按鍵key取值
print(result)

輸出32

dict={'x':32,'y':[1,2,3,4,]}
result=dict['y'][3:]   #按鍵key取值,裏面列表索引爲3的值
print(result)

輸出4

三、如何檢查key是否在字典中?

①has_key()方法 形如:dict.haskey(‘name') 有–>True,無–>False
②in 、not in   形如:'name' in dict      有–>True,無–>False

四、如何更新字典?

①添加一個數據項(新元素)或鍵值對
 dict[new_key] = value 形式添加一個項

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['sex'] = 'female'
print(dict)

出{'Name': 'Zara', 'Age': 7, 'Class': 'First', 'sex': 'female'}

②更新一個數據項(元素)或鍵值對
 dict[old_key] = new_value

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8
dict['School'] = "DPS School"
print(dict['Age'],dict['School'])
print(dict)

輸出

8 DPS School
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}

③刪除一個數據項(元素)或鍵值對
 del  dict[key] 刪除鍵key的項 / del dict 刪除整個字典
 del  dict  刪除字典
 dict.pop(key) 刪除鍵key的項並返回key對應的 value值
 dict.clear() 清空字典全部條目

4、映射類型操做符

標準類型操做符(+,-,*,<,>,<=,>=,==,!=,and,or, not)

a、字典不支持拼接和重複操做符(+,*)
b、字典的比較操做
先比較字典的長度也就是字典的元素個數
      鍵比較
      值比較

5、映射相關的函數

一、len() 計算字典元素個數,即鍵的總數
二、hash() 返回對象的哈希值,能夠用來判斷一個對象可否用來做爲字典的鍵
三、dict() 工廠函數,用來建立字典
四、cmp(dict1, dict2):比較兩個字典元素
五、str(dict):輸出字典可打印的字符串表示
六、type(variable):返回輸入的變量類型,若是變量是字典就返回字典類型

6、字典的方法

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        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
        """
        pass

    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """
        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]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if D has a key k, else False. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None
字典源碼

1. clear(self)清除字典中全部的項

d={}
d['name']='carlos'
d['age']='26'
print(d)
result=d.clear()
print(result)

輸出

{'name': 'carlos', 'age': '26'}
None

2. copy(self) 返回一個具備相同鍵值對的新字典(shallow copy淺複製,由於值自己就是相同的,不是副本)

dict1={'username':'admin','machine':['foo','bar','baz']}
dict2=dict1.copy()
print(dict1)
print(dict2)
dict2['username']='carlos'
print(dict1)
print(dict2)
dict2['machine'].remove('bar')
print(dict1)
print(dict2)

輸出

{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'carlos', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'baz']}
{'username': 'carlos', 'machine': ['foo', 'baz']}

①淺複製shallow copy ,如上,當在副本中替換值的時候原始字典不受影響,可是若是修改了某個值,原始的字典也會隨之改變。

②深複製deep copy,複製其包含的全部值。

from copy import deepcopy
dict={'username':'admin','machine':['foo','bar','baz']}
dict1=dict.copy()
dict2=deepcopy(dict)
print(dict1)
print(dict2)
dict['machine'].remove('bar')
print(dict1)
print(dict2)

輸出

{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}

3. fromkeys(*args, **kwargs) 使給定的鍵創建一個新的字典,每一個鍵對應默認的值都是none

dict1={}
dict2=dict1.fromkeys(['name','age'])
print(dict1)
print(dict2)

輸出{}

       {'name': None, 'age': None}

4. get(self, k, d=None) 更寬鬆的訪問字典項的方法

通常若是試圖訪問字典中不存在的項會報錯,但使用get就不會,而是獲得none值。

dict={'username':'admin','machine':['foo','bar','baz']}
result=dict.get('machine')
print(result)

輸出['foo', 'bar', 'baz']

dict={'username':'admin','machine':['foo','bar','baz']}
result=dict.get('age')
print(result)

輸出None

5. items(self)  將字典全部的項以列表方式返回,列表中的每一項都表示(鍵,值)對的形式,返回時無特定的次序

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.items()
print(result)

輸出 dict_items([('title', 'Python Web Site'), ('url', 'http://www.python.org'), ('spam', 0)]) 

  iteritems 方法大體一致,可是返回一個迭代器對象而不是列表。

6. keys(self) 將字典中鍵以列表方式返回。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.keys()
print(result)

輸出dict_keys(['title', 'url', 'spam'])

   iterkeys 將字典中鍵以列表方式返回,可是返回一個針對鍵的迭代器。   

7.  pop(self, k, d=None) 得到對應給定鍵的值,而後將這個鍵值對從字典中移除。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.pop('url')
print(result)
print(dict)

輸出

http://www.python.org
{'title': 'Python Web Site', 'spam': 0}

   popitem(self) 得到隨機的項,而後將這個項對從字典中移除。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.popitem()
print(result)
print(dict)

輸出

('spam', 0)
{'title': 'Python Web Site', 'url': 'http://www.python.org'}

8.setdefault(self, k, d=None) 得到與給定鍵值相關聯的值,當鍵不存在的時候,返回默認值none且相應的更新字典,當鍵存在的時候,返回對應的值,不改變字典。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.setdefault('url')
print(result)
print(dict)

輸出

http://www.python.org
{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.setdefault('name')
print(result)
print(dict)

輸出

None
{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0, 'name': None}

9. update(self, E=None, **F) 利用一個字典項更新另一個字典

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print(dict)
dict1={'title':'Python Language Site'}
dict.update(dict1)
print(dict)

輸出

{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
{'title': 'Python Language Site', 'url': 'http://www.python.org', 'spam': 0}

10. values(self)  以列表的形式返回字典中的值,返回值的列表中能夠包含重複的元素

     itervalues返回值的迭代器

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print(dict)
result=dict.values()
print(result)

輸出

{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
dict_values(['Python Web Site', 'http://www.python.org', 0])

7、字典鍵的特性  

①不容許同一個鍵出現兩次。建立時若是同一個鍵被賦值兩次,後一個值會被記住

dict={'name':'carlos','age':'26','name':'alex'}
print(dict)

輸出{'name': 'alex', 'age': '26'}

②鍵必須不可變,因此能夠用數,字符串或元組充當,因此用列表就不行

③自動添加,若字典不存在,也能夠爲它賦值,字典就會創建新的項

8、字典的遍歷

一、遍歷字典的key(鍵)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for key in dict.keys():
     print(key)

輸出

Name
Age
Class 

二、遍歷字典的value(值)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for value in dict.values():
     print(value)

輸出

Zara
7
First

三、遍歷字典的項(元素)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for item in dict.items():
     print(item)

輸出

('Name', 'Zara')('Age', 7)('Class', 'First')  

相關文章
相關標籤/搜索