第十六节,基本数据类型,字典dict

字典

常用操作:
  索引
  新增
  删除
  键、值、键值对
  循环
  长度

  字典由键值对组成,由一个键(名称)和 一个值组成,与列表和元组不同的是里面的元素是有键的(名称)

  所以当要打印字典时,打印字典变量加[键]即可

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 a = {
4     "zhs":"1",
5     "ls":"2",
6     "ww":"3"
7 }
8 print(a["ls"])
9 #打印出 2 打印出了ls键的值

创建字典

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {"zhs":"1", "ls":"2", "ww":"3"}
 4 #或者
 5 a = dict({"zhs":"1", "ls":"2", "ww":"3"})
 6 #或者
 7 a = {
 8     "zhs":"1",
 9     "ls":"2",
10     "ww":"3"
11 }
12 #一般采用第三中,更容易读

  索引

  打印字典变量加[要打印的键]

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 print(a["ls"])
 9 print(a["ww"])
10 #打印出 2 3 打印出了ls和ww键的值

  for循环

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 for b in a:
 9     print(b)
10 #打印出 ww zhs ls 默认循环出的是字典的键
11
12 a = {
13     "zhs":"1",
14     "ls":"2",
15     "ww":"3"
16 }
17 for b in a:
18     print(a[b])
19 #打印出 3 1 2 要打印字典变量加上[自定义循环变量,也就是键]才能打印出值

  keys(self)

  """(获取字典的键)""":返回一个字典的键列表

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 a = {
4     "zhs":"1",
5     "ls":"2",
6     "ww":"3"
7 }
8 print(a.keys())
9 #打印出 [‘ww‘, ‘zhs‘, ‘ls‘] 返回字典键列表

  values(self)

  """(获取字典的值)""":返回一个字典的值列表

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 a = {
4     "zhs":"1",
5     "ls":"2",
6     "ww":"3"
7 }
8 print(a.values())
9 #打印出 [‘3‘, ‘1‘, ‘2‘] 返回字典值列表

  items(self)

  """(获取字典里的键和值)""":返回一个字典的键和值列表加元组

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 a = {
4     "zhs":"1",
5     "ls":"2",
6     "ww":"3"
7 }
8 print(a.items())
9 #打印出 [(‘ww‘, ‘3‘), (‘zhs‘, ‘1‘), (‘ls‘, ‘2‘)] 返回字典里的键和值列表加元组

  (keys:获取键) (values:获取值) (items:获取键和值) 结合for循环

  (keys:获取键)结合for循环

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 for b in a.keys():
 9     print(b)
10 #打印出 ww zhs ls 循环出了字典的键

  (values:获取值)结合for循环

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 for b in a.values():
 9     print(b)
10 #打印出 3 1 2 循环出了字典的值

  (items:获取键和值)结合for循环

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 for k, v in a.items(): #因为items()获取的键和值,所以循环里要自定义两个变量分别代表键和值
 9     print(k)
10     print(v)
11 #打印出 ww 3 zhs 1 ls 2 循环出了字典的键和值

  clear(self)

  """(清除字典里的所有内容)"""

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 a.clear()
 9 print(a)
10 #打印出 {} 字典里是空的

  get(self, k, d=None)(推荐使用)

  """ (根据key(键)获取值,如果key(键)不存在可以指定默认值 )""":如果键后面指定了默认值,键存在就获取键自身的值,如果键不存在就获取默认值

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 print(a.get("ls"))
 9 #打印出 2 输出指定键的值
10
11 a = {
12     "zhs":"1",
13     "ls":"2",
14     "ww":"3"
15 }
16 print(a.get("xyz","123")) #xyz键不存在,就获取默认值123
17 #打印出 123 输出指定键的值,如果指定键不存在就输出默认值

  has_key(self, k)

  注意:python3版本以上已经取消了

  """ (:键)key:键,名称 """:返回真或者假

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 a = {
4     "zhs":"1",
5     "ls":"2",
6     "ww":"3"
7 }
8 print(a.has_key("ls"))
9 #打印出 True 返回真说明字典里有ls这个键

  判断字典里是否有某个key键:返回真或者假

  也可以判断字典里是否有某个值

  注意:python3版本以上使用这个方法替代已经取消的has_key

  格式:"要判断的键" in 字典变量.keys()

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 b = "ls" in a.keys()
 9 print(b)
10 #打印出 True 返回真说明字典里有ls这个键
11
12 a = {
13     "zhs":"1",
14     "ls":"2",
15     "ww":"3"
16 }
17 b = "2" in a.values()
18 print(b)
19 #打印出 True 返回真说明字典里有2这个值

  update(self, E=None, **F)

  """ (追加更新)"""要追加更新的变量

  

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 b = {
 9     "z":"4",
10     "l":"5",
11     "w":"6"
12 }
13 a.update(b)
14 print(a)
15 #打印输出 {‘ww‘: ‘3‘, ‘zhs‘: ‘1‘, ‘ls‘: ‘2‘, ‘w‘: ‘6‘, ‘z‘: ‘4‘, ‘l‘: ‘5‘} 将b字典追加更新到了a字典

  删除字典里的元素

    格式:del 字典变量.[要删除的元素键]

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 a = {
 4     "zhs":"1",
 5     "ls":"2",
 6     "ww":"3"
 7 }
 8 del a["ls"]
 9 print(a)
10 #打印输出 {‘ww‘: ‘3‘, ‘zhs‘: ‘1‘} 删除了ls键这个元素

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

时间: 2024-10-03 04:15:12

第十六节,基本数据类型,字典dict的相关文章

第三百一十六节,Django框架,中间件

第三百一十六节,Django框架,中间件 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法. 在django项目的settings模块中,有一个 MIDDLEWARE变量,其中每一个元素就是一个中间件(也就是一个中间件模块的一个类),如下. settings模块中 #中间件 MIDDLEWARE = [ 'django.middleware.security.Securit

第一百二十六节,JavaScript,XPath操作xml节点

第一百二十六节,JavaScript,XPath操作xml节点 学习要点: 1.IE中的XPath 2.W3C中的XPath 3.XPath跨浏览器兼容 XPath是一种节点查找手段,对比之前使用标准DOM去查找XML中的节点方式,大大降低了查找难度,方便开发者使用.但是,DOM3级以前的标准并没有就XPath做出规范:直到DOM3在首次推荐到标准规范行列.大部分浏览器实现了这个标准,IE则以自己的方式实现了XPath. 一.IE中的XPath 在IE8及之前的浏览器,XPath是采用内置基于A

centos mysql 优化 第十六节课

centos mysql  优化  第十六节课 f

第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表、课程评论表、用户收藏表、用户消息表、用户学习表

第三百七十六节,Django+Xadmin打造上线标准的在线教育平台-创建用户操作app,在models.py文件生成5张表,用户咨询表.课程评论表.用户收藏表.用户消息表.用户学习表 创建名称为app_operation的用户操作APP,写数据库操作文件models.py models.py文件 #!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import unicode_literals from datetime i

第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点

第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲-scrapy分布式爬虫要点 1.分布式爬虫原理 2.分布式爬虫优点 3.分布式爬虫需要解决的问题

第三百八十六节,Django+Xadmin打造上线标准的在线教育平台—HTML母版继承

第三百八十六节,Django+Xadmin打造上线标准的在线教育平台-HTML母版继承 母板-子板-母板继承 母板继承就是访问的页面继承一个母板,将访问页面的内容引入到母板里指定的地方,组合成一个新页面返回给浏览器 一般母板里都是写的一个网页里不变的地方,也就是通用的地方,被继承页(访问页)都是每个页面不同的地方,也就是将页面不同的地方引入到母板组合成一个新页面返回浏览器 母板里一般都是网页的.头部.底部.头部底部css.头部底部js 被继承页(访问页)里一般都是新内容,新内容的css和js 母

第三十六节,目标检测之yolo源码解析

在一个月前,我就已经介绍了yolo目标检测的原理,后来也把tensorflow实现代码仔细看了一遍.但是由于这个暑假事情比较大,就一直搁浅了下来,趁今天有时间,就把源码解析一下.关于yolo目标检测的原理请参考前面一篇文章:第三十五节,目标检测之YOLO算法详解 在讲解源码之前,我们需要做一些准备工作: 下载源码,本文所使用的yolo源码来源于网址:https://github.com/hizhangp/yolo_tensorflow 下载训练所使用的数据集,我们仍然使用以VOC 2012数据集

python数据类型:字典dict常用操作

字典是Python语言中的映射类型,他是以{}括起来,里面的内容是以键值对的形式储存的: Key: 不可变(可哈希)的数据类型.并且键是唯一的,不重复的. Value:任意数据(int,str,bool,tuple,list,dict,set),包括后面要学的实例对象等. 在Python3.5版本(包括此版本)之前,字典是无序的. 在Python3.6版本之后,字典会按照初建字典时的顺序排列(即第一次插入数据的顺序排序). 当然,字典也有缺点:他的缺点就是内存消耗巨大. 优点:查询速度快,映射型

PHP中on回调的实现(十六节)

各位好,我是老李.和老李一同完成<PHP网络编程>,虽然我知道实际上从头到尾可能只有我一个人在搞.我告诉你们一定要好好在家好好学习.远程工作,不要折腾地自己最后连班都没法上了,要好好学习.要不断学习.要终身学习. 上个章节我送了大家一篇番外: 同步异步阻塞非阻塞,了解一下?(十三节) 今天这篇是和上篇番外紧密结合的,因为我答应大家了,要通过今天这一篇中的代码表演一波儿啥叫阻塞.啥叫非阻塞.啥叫异步非阻塞...这年月,听到的异步非阻塞次数太TM多了,似乎每个高IO的程序都离不开这个组合词! 这个