Python基本數據類型之dict

1、建立字典:

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

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

2、基本操做:

索引

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

鍵、值、鍵值對

keys():獲取全部鍵
values():獲取全部值
items():獲取全部鍵值對python

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]中則會報錯。app

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值移除指定的鍵值對python2.7

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()用法同樣this

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

del d["name"]
print(d)

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

判斷

用in就能夠了,可是在python2.7中可使用has_key()code

批量更新

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

3、源碼

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
相關文章
相關標籤/搜索