python--字典dict

xie仗劍天涯發表於2017-03-09

字典由多個鍵與其對應的值構成的對組成,是另一種可變容器模型,且可儲存任意型別物件。字典的每個鍵值用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中。

注:字典中的鍵是唯一的(其他型別的對映也是如此),而值不是唯一的。

字典類似於你通過聯絡人名字查詢地址和聯絡人詳細情況的地址簿.即,我們把鍵(名字)和值(詳細情況)聯絡在一起。注意,鍵必須是唯一的,字典中的鍵/值對是沒有順序的(字典是無序的)。如果想要一個特定的順序,那麼應該在使用前自己對它們排序。字典是dict類的例項/物件。

字典是python中唯一的內建對映型別

1.dict 函式

使用dict 函式,通過其他對映(其他字典或鍵-值)這樣的序列對建立字典

items = [("name","zhangsan"),("age",28),("job","educator")]
D = dict(items)
print (D)
print (type(D))

2. 字典的格式化字串

一個電話本為例子的字典程式碼(引用格式化字串)

phonebook = {
    "zhangsan":{
        "phone":"01012345",
        "addr":"tianhedong 32 hao",
    },
    "lisi":{
        "phone":"02023456",
        "addr":"huangpunan 54 hao",
    },
    "zhaowu":{
        "phone":"03034567",
        "addr":"tianhebei 17 hao",
    },
    "xiesen":{
        "phone":"06054321",
        "addr":"tianhexi 12 hao",
    },
}

labels ={
    "phone":"phone numbers",
    "addr":"address"
}

name = input ("please input your name:")

if "request" == "p" :key = "phone"
if "request" == "a" :key = "addr"
if name in phonebook :
    print ("%s's %s is %s." %(name, labels[key], phonebook[name][key]))

字典的方法

1. clear

clear 清除字典的所有項.類似list.sort ,無返回值

D = {}
D["name"] = "xieshengsen"
D["age"] = 25

print (D)

returned_value = D.clear()

print (D)
print (returned_value)

2. copy

copy 返回一個具有相同鍵值對的新字典(淺複製)

Q = {"username":"admin","machines":["foo","bar","baz"]}
QQ = Q.copy()
print (Q)
print (QQ)

QQ["username"] = "Administrator"
QQ["machines"].remove("bar")

print(Q)
print(QQ)

深複製

form copy import deepcopy

import copy

d = {}
d["names"] = ["hello","world"]

print (d)

dd = copy.copy(d)
dc = copy.deepcopy(d)
d["names"].append("haha")

print (d)
print (dd)
print(dc)

3. fromkeys

fromkeys 使用給定的鍵建立新的字典,每個鍵預設對應的值為none

print({}.fromkeys(["name","age"])) # none 作為預設值

print(dict.fromkeys(["name","age"]),"(unknown)") # 修改unknown 為預設值

4. get

get 更寬鬆的訪問字典項的方法(一般來說,如果訪問字典中不存在的項時會出錯,使用get訪問不會出現錯誤)

AA = {}
# print (AA["name"])  # 出現錯誤

print (AA.get("name"))  # 鍵值不存在,輸出結果None

AA["name"]= "xieshengsen"
print (AA.get("name"))

5. items 和iteritems

items 方法將所有的字典項以列表方式返回,這些列表項中的每一項都是來自(鍵-值)。但是項在返回時並沒有特殊的順序。

II = {"title": "python web site","url":"https://www.python.org","spam":0}
print (II.items())

iteritems 會返回一個迭代器 而不是列表(python3 已經沒有iteritems 這個方法)

6. keys 和iterkeys

keys 方法將字典的鍵以列表形式返回,而iterkeys 則返回針對鍵的迭代器

7. pop

pop 方法用來獲取對應於給定的鍵的值,然後將這個鍵-值對從字典中移除

dd = {"hh":1,"yy":2,"vv":3,"gg":4}
print (dd.pop("hh"))
print (dd)

8. popitem

popitem 方法類似於list.pop,後者會彈出列表的最後一個元素。但,popitem彈出隨機項,因為字典沒有“最後元素”的概念(字典是無序的).

p = {"url":"https://www.python.org/","spam":0,"title":"python web site"}
print (p.popitem())
print (p)

9. setdefault

setdefault 類似於get方法,能夠獲得與給定鍵相關聯的值,setdefault還能在字典中不含有給定鍵的情況下設定相應的鍵值

set = {}
print (set.setdefault("name","N/A"))
print (set)

set["name"] = "zhangsan"
print (set.setdefault("name","N/A"))
print (set)

當鍵不存在時,setdefault 返回預設值並相應的更新字典,如果鍵存在,返回其相應值,但不改變字典。

10. update

update 方法是利用一個字典項更新另外一個字典.

up = {"color":"red","number":"1234","animal":"Bear","Fruits":"apples"}
da = {"Stationery":"book","food":"milk"}
up.update(da)
print (up)

提供的字典的項會被新增到舊字典中,相同的鍵會被覆蓋

11. values

values 方法以列表的形式返回字典的值(itervalues 返回值的迭代器,python3 沒有),與返回值的列表不同的是,返回值列表中可以包含重複的元素。

valu = {}
valu[1]=1
valu[2]=2
valu[3]=3
valu[4]=1
print (valu.values())

字典dict官方解析

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

相關文章