Python基本資料型別之dict

morra發表於2016-10-13

一、建立字典:

d = {
    "name": "morra",        #字典是無序的
    "age": 99,
    "gender": 'm'
}

a = dict()
b = dict(k1=123,k2="morra")

二、基本操作:

索引

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}
print(d["name"])

鍵、值、鍵值對

keys():獲取所有鍵
values():獲取所有值
items():獲取所有鍵值對

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}

print(d.keys())
print(type(d.keys()))

print(d.values())
print(type(d.values()))

print(d.items())
print(type(d.items()))

OUTPUT:
dict_keys(['gender', 'age', 'name'])
<class 'dict_keys'>

dict_values(['m', 99, 'morra'])
<class 'dict_values'>

dict_items([('gender', 'm'), ('age', 99), ('name', 'morra')])
<class 'dict_items'>

迴圈

for a in d:         #字典在for中預設只能迭代輸出key
    print(a)        

OUTPUT:
name
gender
age

#------------------

for i in d.keys():      #迭代輸出key
    print(i)

OUTPUT:
name
gender
age

#------------------

for j in d.values():    #迭代輸出value
    print(j)

OUTPUT:
morra
m
99

#------------------

for k,v in d.items():   #迭代輸出鍵值對
    print(k,v)

OUTPUT:
name morra
gender m
age 99

取值

實際上,在使用字典取值的時候使用最多的方法是get()而不是dict[key],因為如果當key值不存在時,使用get()可以呼叫一個預設值,但是在dict[key]中則會報錯。

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}
val1 = d.get('age')
val2 = d.get('get','123')    #為key設定預設值
print(val1,val2)

OUTPUT:
99 123

刪除

pop(k):根據key值移除指定的鍵值對

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}

d.pop("name")
print(d)

OUTPUT:
{'gender': 'm', 'age': 99}

popitem():從當前尾部移除鍵值對,由於字典是無序的,因此被移除的鍵值對也是隨機的。

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}

d.popitem()        
print(d)

del:刪除指定索引的鍵值對,和pop()用法一樣

d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}

del d["name"]
print(d)

OUTPUT:
{'age': 99, 'gender': 'm'}

判斷

用in就可以了,但是在python2.7中可以使用has_key()

批量更新

update()方法只會更新與原來不同的鍵值對:

  • 如果key一樣,value不一樣,則會把原來的value覆蓋掉。
  • 如果key不一樣則會把兩個鍵值對都新增進來。
  • 如果有一個鍵值對的key、value和原來一樣,則不會更新。
d = {
    "name": "morra",
    "age": 99,
    "gender": 'm'
}

d1 = {
    "name": "morra",
    "age1": 991,
    "gender1": 'm1'
}

d.update(d1)
for k,v in d.items():
    print(k,v)

OUTPUT:
name morra
age1 991
gender1 m1
gender m
age 99

補充

  • fromkeys():
    由於list在迭代的時候沒有隻有一個值,所以不能直接使用dict(li)把列表轉換為字典。在這裡我們需要使用字典裡的fromkeys()方法。
    fromkeys() :函式用於建立一個新字典,列表中的元素當做key,併為每個key設定一個固定值(value是可選的,如果沒有預設為None)。
seq = ("name","key")
a = dict.fromkeys(seq)
b = dict.fromkeys(seq,1)

print(a)
print(b)

OUTPUT:
{'key': None, 'name': None}
{'key': 1, 'name': 1}
  • @staticmethod
    一般來說,要使用某個類的方法,需要先例項化一個物件再呼叫方法,或直接用類呼叫。而使用staticmethod裝飾器之後,就可以不需要例項化,直接類名.方法名()來呼叫。
    這有利於組織程式碼,把某些應該屬於某個類的函式給放到那個類裡去,同時有利於名稱空間的整潔。
@staticmethod 
def fromkeys(*args, **kwargs):
    """ 
    Returns a new dict with keys from iterable and values equal to value. 
    """
    pass
    

三、原始碼

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): 
        """清空字典"""
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): 
        """ D.copy() -> a shallow copy of D """
        pass

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

    def get(self, k, d=None): 
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def items(self): 
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): 
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): 
        """
        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): 
        """
        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): 
        """ 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): 
        """ D.values() -> an object providing a view on D's values """
        pass

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

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

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

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

    def __getitem__(self, y): 
        """ x.__getitem__(y) <==> x[y] """
        pass

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

    def __gt__(self, *args, **kwargs): 
        """ 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): 
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): 
        """ Return len(self). """
        pass

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

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

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

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

    def __repr__(self, *args, **kwargs): 
        """ Return repr(self). """
        pass

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

    def __sizeof__(self): 
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

相關文章