python入门到放弃(七)-基本数据类型之dcit字典

1.概述

字典是python中惟一的一个映射类型,以{}大括号括起来的键值对组成

字典中的key是惟一的,必须是可hash,不可变的数据类型

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

#扩展:python

可哈希(不可变)的数据类型:int,str,tuple,bool
不可哈希(可变)的数据类型:list,dict,set

 

#先来看看dict字典的源码写了什么,方法:按ctrl+鼠标左键点dictapi

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

 

#演示什么数据类型能做为keyapp

# 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增长ide

#关键字
# 一、setdefault('键','值')
# 二、变量['key'] = 'value'

#例子:ui

dic = {'广东':'广州','山东':'济南','海南':'三亚'}
dic['湖南'] = '长沙' #新增,前面是key,后面是值
print(dic)
#{'广东': '广州', '山东': '济南', '海南': '三亚', '湖南': '长沙'}

dic.setdefault('广西','桂林')
# 使用setdefault须要注意的是若是在字典中存在就不进行任何操做,不存在就进行添加
print(dic)
#{'广东': '广州', '山东': '济南', '海南': '三亚', '广西': '桂林'}

 

#2.2删除this

#关键字
1、pop()
二、del dic[''] #
三、clear()   #清空
四、popitem  #随机删除
五、要注意的是字典没有remove这个删除命令

#例子:spa

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.修改3d

#关键字
一、dic[''] = ''
二、dic.update(dic1)

#例子:rest

dic = {'广东':'广州','山东':'济南','海南':'三亚'}
dic[
"广东"] = '湖北' #须要注意的是前边的修改是键key,而后等号后面修改的value值 print(dic) #{'广东': '湖北', '山东': '济南', '海南': '三亚'} dic1 = {'战狼':'吴京','亮剑':'李云龙','山东':'淮上'} dic.update(dic1) print(dic) #{'广东': '湖北', '山东': '淮上', '海南': '三亚', '战狼': '吴京', '亮剑': '李云龙'} #把dic1中的内容更新到dic中,若是key重名,则修改替换,若是不存在key,则新增

 

#2.4.查询code

# 关键字
# 一、使用for循环获取,获取到的是键,不是值
# 二、print(dic['']) #查询键,返回值
# 三、print(dic.get(''))  #若是没有查询到的话就会返回None
# 四、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
相关文章
相关标签/搜索