python入門到放棄(七)-基本數據類型之dcit字典

1.概述

字典是python中唯一的一個映射類型,以{}大括號括起來的鍵值對組成

字典中的key是唯一的,必須是可hash,不可變的數據類型

語法:{key1:value,key2:value}

#擴展:

可哈希(不可變)的數據類型:int,str,tuple,bool
不可哈希(可變)的數據類型:list,dict,set

 

#先來看看dict字典的源碼寫了什麼,方法:按ctrl+鼠標左鍵點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(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

dict
View Code

 

#演示什麼數據類型能作爲key

# dic = {'name':'guoke','age':22} #字符串可以爲鍵(key)

# dic = {1:'a',2:'b',3:'c'} #數字可以爲鍵

# dic = {True:'1',False:'2'} #布爾值可以爲鍵

# dic = {(1,2,3):'abc'} #元組也可以爲鍵

# dic = {[1,2,3]:'abc'} #列表不能爲鍵{key:vaule} 

 

2.字典的增刪改查

#2.1增加

#關鍵字
# 1、setdefault('鍵','值')
# 2、變量['key'] = 'value'

#例子:

dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
dic['湖南'] = '長沙' #新增,前面是key,後面是值
print(dic)
#{'廣東': '廣州', '山東': '濟南', '海南': '三亞', '湖南': '長沙'}

dic.setdefault('廣西','桂林')
# 使用setdefault需要注意的是如果在字典中存在就不進行任何操作,不存在就進行添加
print(dic)
#{'廣東': '廣州', '山東': '濟南', '海南': '三亞', '廣西': '桂林'}

 

#2.2刪除

#關鍵字
1、pop()
2、del dic[''] #
3、clear()   #清空
4、popitem  #隨機刪除
5、要注意的是字典沒有remove這個刪除命令

#例子:

dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
ret
= dic.pop('廣東') #通過key刪除,返回被刪除的value print(ret) #廣州 :可以查看到的是通過key將值爲廣州刪除了 print(dic) #{'山東': '濟南', '海南': '三亞'} del dic['山東'] #要注意刪的時候只能是寫key,不能寫value刪 print(dic) #{'廣東': '廣州', '海南': '三亞'} dic.clear() #{} #清空 print(dic) #{} ret = dic.popitem() #隨機刪除,返回值 一個元組(key,value) print(ret) #('海南', '三亞') print(dic) #{'廣東': '廣州', '山東': '濟南'}

 

#2.3.修改

#關鍵字
1、dic[''] = ''
2、dic.update(dic1)

#例子:

dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
dic[
"廣東"] = '湖北' #需要注意的是前邊的修改是鍵key,然後等號後面修改的value值 print(dic) #{'廣東': '湖北', '山東': '濟南', '海南': '三亞'} dic1 = {'戰狼':'吳京','亮劍':'李雲龍','山東':'淮上'} dic.update(dic1) print(dic) #{'廣東': '湖北', '山東': '淮上', '海南': '三亞', '戰狼': '吳京', '亮劍': '李雲龍'} #把dic1中的內容更新到dic中,如果key重名,則修改替換,如果不存在key,則新增

 

#2.4.查詢

# 關鍵字
# 1、使用for循環獲取,獲取到的是鍵,不是值
# 2、print(dic['']) #查詢鍵,返回值
# 3、print(dic.get(''))  #如果沒有查詢到的話就會返回None
# 4、print(dic.setdefault(''))

#例子:

dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
# for i in dic:
#     print(i) #for循環默認是獲取字典中的鍵
# 廣東
# 山東
# 海南

print(dic['廣東'])   #查看1,如果沒有這個鍵的時候查詢就會報錯
# print(dic['湖北'])  #報錯,NameError: name '湖北' is not defined

print(dic.get('廣東','這個是沒有的'))  #查看2,沒有返回None,可以指定返回內容
#廣州

print(dic.get('廣西')) #None,因爲沒有這個key
print(dic.setdefault('廣東'))  #如果沒有的話也是返回None

#2.5.字典的其他操作(特有)

#keys  #獲取到字典中的每一個鍵
#value  #獲取到字典中的值
#itmes   #獲取到字典中的鍵值對數據

#例子:

dic = {"id":123,"name":"cw","age":22,"ok":"大佬"}
print(dic.keys())  #(高仿列表)

for i in dic.keys():
    print(i)
#獲取到鍵:id,name,age,ok

for i in dic:
    print(i)   #以上的幾種方法都是獲取到字典中的每一個鍵
#獲取到id,name,age,ok

print(dic.values())
for i in dic.values():  #獲取到字典中的每一個值
    print(i)
#獲取到值:123,cw,22,大佬

for i in dic.items():  #獲取到鍵值對
    print(i)
# ('id', 123)
# ('name', 'cw')
# ('age', 22)
# ('ok', '大佬')

 

3.字典的嵌套

嵌套就是一層套着一層,字典套着字典

#演練:

#寫字典嵌套來查找
dic1 = {
           "name": "張世豪",
           "age": 18,
           "wife": {
                 "name": '大哥成',
                 "age": 28 },
           "children": ['第⼀個毛孩子', '第⼆個毛孩子'],
           "desc": '峯哥不不會告我吧. 沒關係. 我想上頭條的'
              }

#通過key取查找,使用get
#1.查找大哥成
#思路:首先可以看到大哥成是作爲wife鍵的值,所以可以先找wife鍵,拿到值,再接着獲取鍵name,打印出它的value值
print(dic1.get("wife")) #{'name': '大哥成', 'age': 28}
print(dic1.get("wife").get("name")) #大哥成

#2.查看28
#思路:和上面一樣,通過找出鍵獲取到值
print(dic1.get("wife").get("age")) #28

#3.查找第一個毛孩子
#思路:同樣是通過鍵找出值,然後通過索引進行獲取
print(dic1.get("children")[0]) #第⼀個毛孩子

#嵌套練習

dic1 = {
    'name':['guo',2,3,5],
    'job':'teacher',
    'dianshi':{'haijun':['python1','python2',100]}
}
#要求
# 1,將name對應的列表追加⼀個元素’ke’。
# 2,將name對應的列表中的guo首字母大寫。
# 3,dianshi對應的字典加一個鍵值對’蔣小魚’,’niubi’。
# 4,將dianshi對應的字典中的haijun對應的列表中的python2刪除
#
s1 = (dic1.get('name'))
s1.append('ke')
print(s1) #['guo', 2, 3, 5, 'ke']

print(dic1.get('name')[0].capitalize()) #Guo

dic1['蔣小魚'] = 'niubi'
print(dic1) #{'name': ['guo', 2, 3, 5], 'job': 'teacher', 'dianshi': {'huijun': ['python1', 'python2', 100]}, '蔣小魚': 'niubi'}

dic2 = (dic1.get('dianshi').get('haijun').pop(1))
print(dic2) #python2
print(dic1)
#{'name': ['guo', 2, 3, 5], 'job': 'teacher', 'dianshi': {'haijun': ['python1', 100]}}
View Code

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章