1. 程式人生 > >Python 資料型別--字典(dict)基本操作

Python 資料型別--字典(dict)基本操作

1、定義
person={'name':'zyb','addr':'hainan'}
person=dict({'name':'zyb','addr':'hainan'})

2、查詢
通過字典中的key,查詢對應的資料
person['name']
person.get('name')

3、新增
person['sex']='男'


4、刪除
person.pop('sex')
del person['sex']

5、獲取key,value 和key and values
5.1 獲取key
person.keys() ,返回一個列表
5.2 獲取value
person.values(),返回一個列表
5.3 獲取key-value
person.items(),返回一個列表

6、迴圈
# key 的迴圈
for key in person:
    print(key)


for key in person。keys():
    print(key)


#value的迴圈
for value in person.values():
    print(value)

#key-value的迴圈
for key,value in person.items():
    print(key,value)
返回一個元祖
7、長度
len(person)


字典類的原始碼:

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(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根據key獲取值,d是預設值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 所有項的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 項可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D's keys """
        return []

    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__
        """ 如果key不存在,則建立,如果存在,則返回已存在的值且不修改 """
        """ 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
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, 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() -> list of D's values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有項,只是將內容儲存至view物件中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass

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

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

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

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

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

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

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

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

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

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        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): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

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

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

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

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

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

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

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

    __hash__ = None


相關推薦

Python 資料型別--字典(dict)基本操作

1、定義 person={'name':'zyb','addr':'hainan'} person=dict({'name':'zyb','addr':'hainan'}) 2、查詢 通過字典中的key,查詢對應的資料 person['name'] person.get('

Python資料型別dict相關常用操作

info = {     'stu1101': "TengLan Wu",     'stu1102': "LongZe Luola",     'stu1103': "XiaoZe Maliya"

Python資料型別------字典

    在Python中,字典是一系列的鍵-值對,每個鍵都與一個值相關聯,可以使用鍵來訪問與之相關聯的值,這個值可以是數字、字串、列表乃至字典。可以說字典中鍵所對應的值是任何Python物件。在Python中、字典用花括號{}中的一系列鍵值來表示。鍵和值之間用冒號:來分割,而

Python——資料型別dict

字典,相當於一個列表,不過列表的索引是數字,字典的索引是數字或者字串。 1、字典的訪問 字典是典型的key-value結構,一個key對應著一個value,key就是索引,value就是要儲存的值 score={'Albert':99, 'QQ':88} print(score['Albert']

Python資料分析庫pandas基本操作

pandas是什麼? 是它嗎? 。。。。很顯然pandas沒有這個傢伙那麼可愛。。。。 我們來看看pandas的官網是怎麼來定義自己的: pandas is an open source, easy-to-use data structures and data an

python資料結構---字典(Dict)

基本操作方法: d = {'age':18, 'name':'liu', 'sex':'male'} # 1.遍歷字典 for k in d: print k # 結果:age name sex for k in d.keys(): print k # 結

python資料型別dict(map)

字典 一.建立字典 方法①: >>> dict1 = {} >>> dict2 = {'name': 'earth', 'port': 80} >>> dict1, dict2 ({}, {'port': 80, 'na

python資料型別 字典 dictionnary(無序)

字典dic什麼是字典:    字典是一種可變的容器, 可以儲存任意型別的資料    字典中的每一個數據都是用鍵進行索引的,而不像序列可以用下標    (index) 來進行索引    字典中的資料沒有先後的順序關係, 字典的儲存是無序的    字典中的資料以鍵(key)-值(

python--資料型別-字典

字典1)關鍵字: dict       dictionary,符號為花括號:{ }2)type(變數名/值)---->可以獲取資料的型別3)如果你的字典只有一個數據,仍然是字典4)字典的資料組成:key:value的   (key用雙引號或單引號括起來)5)字典的資料值

python資料型別字典(dict)和其常用方法

字典的特徵: key-value結構key必須可hash,且必須為不可變資料型別、必須唯一。 # hash值都是數字,可以用類似於2分法(但比2分法厲害的多的方法)找。可存放任意多個值、可修改、可以不唯一無序查詢速度快常用方法: info = {'stu01': 'alex', 'stu02':

python中的資料型別——字典dict

字典的建立 字典 key-value 鍵值對儲存的一種資料結構 value值可以是任意資料型別:int float long list tuple set dict 定義一個空字典 In [1]: d = {} In [2]: type(d)

python全棧_011_Python3基本資料型別--字典

1:什麼是字典?:   dict,以{} 來表示,使用逗號來隔開,內部元素使用key:value的形式來儲存資料,key必須是不可變的資料型別,value可以是任何型別的資料型別。  已知不可變的資料型別:int,str,bool,tuple  可變的資料型別: list,dict,set  語法:    

python基礎資料型別dict字典)和近期知識點總結__005

字典dict 1、資料型別劃分:可變資料型別,不可變資料型別 (1)不可變資料型別(可雜湊):str、int、bool、元組 (2)可變資料型別(不可雜湊):dict、list、set 2、dict: key必須是不可變資料型別:可雜湊,鍵一般是唯一的,如果重複,會替換前面的,值

Python 資料型別基本操作

【概述】 不同的資料,需要定義不同的資料型別。 Python 定義了五個標準型別,用於儲存各種型別的資料: Numbers(數字) String(字串) List(列表) Tuple(元組) Dictionary(字典) 【數字】 數字資料型別用於儲存數值,它

python 資料型別 dict(字典)

快捷鍵複習 alt + enter 匯入需要的模組。 alt + r 替代 ctrl+ / 註釋 ctrl + shitf + F 專案內查詢關鍵字 ctrl + f 檔案內查詢關鍵字 字串的方法複習 find

Python基礎資料型別(五) dict字典

字典dict{} 字典數字自動排序 enumerate 列舉 for i,k in enumerate(dic,1) #第二個引數預設不寫就是0 ---列舉 print(i,k) dict,以{}來表示每一項用逗號隔開,內部元素用 key:value的形式來儲存 定義 dict_l

python字典基本操作

特性 什麽是 圖片 src odin utf key值 author display 字典的基本方法 什麽是字典: 字典是一種 key - value的數據類型,聽alex說就像我們上學用的字典,通過筆劃,字母來查找對飲頁面的詳細內容。 語法: id_dict = {

java在處理基本資料型別加減乘除操作注意

1.int /int 得到的結果轉double 舉例: int a=1; int b=2; double d=a/b 上面結果通常認為是0.5 ,但結果是0.0;正確的是: int a=1; int b=2; double d=(double)a/b   2. do

python資料型別(string/list/tuple/dict)內建方法

Python 字串常用方法總結 明確:對字串的操作方法都不會改變原來字串的值 1,去掉空格和特殊符號 name.strip()  去掉空格和換行符 name.strip('xx')  去掉某個字串 name.lstrip()  去掉左邊的空格和換行符