前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python入门到放弃(七)-基本数据类型之dcit字典

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

作者头像
老油条IT记
发布2020-03-20 21:07:50
5840
发布2020-03-20 21:07:50
举报
文章被收录于专栏:用户7095785的专栏

1.概述

代码语言:javascript
复制
字典是python中唯一的一个映射类型,以{}大括号括起来的键值对组成

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

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

#扩展:

代码语言:javascript
复制
可哈希(不可变)的数据类型:int,str,tuple,bool
不可哈希(可变)的数据类型:list,dict,set

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

代码语言:javascript
复制
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

#演示什么数据类型能作为key

代码语言:javascript
复制
# 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增加

代码语言:javascript
复制
#关键字
# 1、setdefault('键','值')
# 2、变量['key'] = 'value'

#例子:

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

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

#2.2删除

代码语言:javascript
复制
#关键字
1、pop()
2、del dic[''] #
3、clear()   #清空
4、popitem  #随机删除
5、要注意的是字典没有remove这个删除命令

#例子:

代码语言:javascript
复制
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.修改

代码语言:javascript
复制
#关键字
1、dic['键'] = '值'
2、dic.update(dic1)

#例子:

代码语言:javascript
复制
dic = {'广东':'广州','山东':'济南','海南':'三亚'}

dic["广东"] = '湖北' 
#需要注意的是前边的修改是键key,然后等号后面修改的value值
print(dic) #{'广东': '湖北', '山东': '济南', '海南': '三亚'}

dic1 = {'战狼':'吴京','亮剑':'李云龙','山东':'淮上'}
dic.update(dic1)
print(dic)
#{'广东': '湖北', '山东': '淮上', '海南': '三亚', '战狼': '吴京', '亮剑': '李云龙'}
#把dic1中的内容更新到dic中,如果key重名,则修改替换,如果不存在key,则新增

#2.4.查询

代码语言:javascript
复制
# 关键字
# 1、使用for循环获取,获取到的是键,不是值
# 2、print(dic['']) #查询键,返回值
# 3、print(dic.get(''))  #如果没有查询到的话就会返回None
# 4、print(dic.setdefault(''))

#例子:

代码语言:javascript
复制
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.字典的其他操作(特有)

代码语言:javascript
复制
#keys  #获取到字典中的每一个键
#value  #获取到字典中的值
#itmes   #获取到字典中的键值对数据

#例子:

代码语言:javascript
复制
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.字典的嵌套

代码语言:javascript
复制
嵌套就是一层套着一层,字典套着字典

#演练:

代码语言:javascript
复制
#写字典嵌套来查找
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]) #第⼀个毛孩子

#嵌套练习

代码语言:javascript
复制
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]}}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.概述
  • 2.字典的增删改查
  • 3.字典的嵌套
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档