• [Python]字典的简单用法


      Python中的字典与现实中字典类似,从字典中可以找到“”字:鱼类是体被骨鳞、以鳃呼吸、通过尾部和躯干部的摆动以及鳍的协调作用游泳和凭上下颌摄食的变温水生脊椎动物。类比到Python的字典中,把“鱼”这个字称为“键(key)”,把其对应的含义称为“值(value)”。

      字典是Python中唯一的映射类型,映射是数学上的一个术语,指两个元素集之间相互对应的关系。

      

      字典的几种创建方法

    1 dict1=dict((('F',70),('i',105),('s',115),('h',104),('c',67)))
    2 dict2=dict(F=70,I=105,S=115,H=104,C=67)
    3 dict3=dict((('F',70),('I',105),('S',110)))

      字典的内置方法:

      1.fromkeys()

      fromkeys()方法用于创建并返回一个新的字典,有两个参数,第一个是字典的键,第二个是可选的值,若不输入则默认为None。

    dict3={}
    print(dict3.fromkeys((1,2,3)))
    dict4={}
    print(dict4.fromkeys((1,2,3),"Number"))

      输出结果则是:

      {1: None, 2: None, 3: None}
      {1: 'Number', 2: 'Number', 3: 'Number'}

      2.keys(),values(),items()

      keys()用于返回字典中的键,values()用于返回字典中的所有的值,items()用于返回字典中所有的键值对应关系。

    dict5={}
    dict5=dict5.fromkeys(range(5),"1")
    print(dict5.keys())
    print(dict5.values())
    print(dict5.items())

      输出结果是:

      dict_keys([0, 1, 2, 3, 4])
      dict_values(['1', '1', '1', '1', '1'])
      dict_items([(0, '1'), (1, '1'), (2, '1'), (3, '1'), (4, '1')])

       3.get()

      如果直接访问不存在的字典项:

    dict5={}
    dict5=dict5.fromkeys(range(5),"1")
    print(dict5[5]);

      则会报错:

      Traceback (most recent call last):
         File "D:/python/test.py", line 3, in <module>
        print(dict5[5]);
      KeyError: 5

      get()方法提供了更宽松的访问字典的方法,如果访问字典项不存在不会报错,而是返回一个None值:

    dict5={}
    dict5=dict5.fromkeys(range(5),"1")
    print(dict5.get(5));

      结果返回None。

      4.copy()  复制字典

    a={1:"one",2:"two",3:"three"}
    b=a.copy()
    print(b,"1")
    a.clear()
    print(b,"2")

      

      5.pop()和popitem()

      pop()是给定键弹出对应值,而popitem是弹出一个项。

    a={1:"one",2:"two",3:"three",4:"four"}
    print(a.pop(2))
    print(a)
    print(a.popitem(),a.popitem())
    print(a)

      结果:

      two
      {1: 'one', 3: 'three', 4: 'four'}
      (4, 'four') (3, 'three')
      {1: 'one'}

      

      6.update()

      用来更新字典。

    pets={"米奇":"老鼠","汤姆":"","小白":""}
    print(pets)
    pets.update(小白="")
    print(pets)
  • 相关阅读:
    对List进行子查询及分组
    网格数据库架构设计构想
    推荐一款简单实用的漏洞测试工具:Paros
    用友U9产品SOA设计架构遭技术质疑
    超简单使用MemCached
    不按常规出招
    如何学好AJax、求高手指点
    Begin
    SpringBoot基础
    SpringBoot基础学习(番外9.1)Spring MVC或Spring Boot配置默认访问页面不生效?
  • 原文地址:https://www.cnblogs.com/zlc364624/p/11593984.html
Copyright © 2020-2023  润新知