美文网首页
009.Python字典

009.Python字典

作者: Jenlte | 来源:发表于2018-07-19 22:02 被阅读0次

    Python 字典

    1. 概述

    字典是另一种可变容器模型,且可存储任意类型对象。

    字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

    dict = {"name":"Jentle","age":18,"height":182.5}
    print(dict)#{'name': 'Jentle', 'age': 18, 'height': 182.5}
    

    键必须是唯一的,但值则不必。

    值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

    一个简单的字典实例:

    #键必须是不可变的,如字符串、数字或元组
    tup1 = ("123",1,1.2)
    dict = {"name":"Jentle",2:18,tup1:182.5}
    print(dict[2])#18
    print(dict[tup1])#182.5
    

    如果用字典里没有的键访问数据,会输出错误如下:

    dict = {"name":"Jentle","age":18,"height":182.5}
    print(dict["weight"])
    
    #output:
    Traceback (most recent call last):
      File "D:/Python/PythonCode/002PythonBasic/day002/00PythonNote.py", line 3, in <module>
        print(dict["weight"])
    KeyError: 'weight'
    

    防止字典里没有键访问报错,可以用get方法

    dict = {"name":"Jentle","age":18,"height":182.5}
    print(dict.get("weight",None))#output:None
    

    2. 修改字典

    向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

    dict = {"name":"Jentle","age":18,"height":182.5}
    dict["age"] = 19 #更新
    dict["weight"] = 75 #添加
    print ("dict['age']: ", dict['age'])
    print ("dict['weight']: ", dict['weight'])
    

    3. 删除字典元素

    能删单一的元素也能清空字典,清空只需一项操作。

    显式删除一个字典用del命令,如下实例:

    dict = {"name":"Jentle","age":18,"height":182.5}
    print(dict) #{'name': 'Jentle', 'age': 18, 'height': 182.5}
    del dict["age"]
    print(dict) #{'name': 'Jentle', 'height': 182.5}
    dict.clear() #清空字典
    print(dict) #{}
    del  dict #删除字典
    

    4. 字典键的特性

    字典值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。

    两个重要的点需要记住:

    • 1.不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
    dict = {"name":"Jentle","age":18,"height":182.5,"age":19}
    print(dict) #{'name': 'Jentle', 'age': 18, 'height': 182.5}
    
    • 2.键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,如下实例:
    dict = {["name"]:"Jentle","age":18,"height":182.5,"age":19}
    print("dict[]",dict["[name]"])
    
    #output:
    
    Traceback (most recent call last):
     File "D:/Python/PythonCode/002PythonBasic/day002/00PythonNote.py", line 2, in <module>
       dict = {["name"]:"Jentle","age":18,"height":182.5,"age":19}
     TypeError: unhashable type: 'list'
    
    

    5. 字典内置函数&方法

    序号 函数及描述 实例
    1 len(dict)计算字典元素个数,即键的总数。 >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(dict) 3
    2 str(dict)输出字典,以可打印的字符串表示。 >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> str(dict)"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
    3 type(variable)返回输入的变量类型,如果变量是字典就返回字典类型。 >>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}>>> type(dict)<class 'dict'>
    dict = {"name":"Jentle","age":18,"height":182.5,"age":19}
    print(len(dict)) # 3
    dictStr = str(dict)
    print(dictStr)
    dictType = type(dict)
    print(dictType)
    
    #fromkeys
    seq = ('Google', 'Runoob', 'Taobao')
    
    dict = dict.fromkeys(seq)
    print("dict.fromkeys(seq) : %s" % str(dict))#dict.fromkeys(seq) : {'Google': None, 'Runoob': None, 'Taobao': None}
    
    dict = dict.fromkeys(seq, 10)
    print("dict.fromkeys(seq, 10) : %s" % str(dict))#dict.fromkeys(seq, 10) : {'Google': 10, 'Runoob': 10, 'Taobao': 10}
    
    #字典 get() 方法
    dict = {"name":"Jentle","age":18,"height":182.5,"age":19}
    value1 = dict.get("name","default")
    value2 = dict.get("sex","未设置")
    print("value1=",value1)#value1= Jentle
    print("value2=",value2)#value2= 未设置
    
    # 字典 items() 方法:以列表返回可遍历的(键, 值) 元组数组
    dict = {"name":"Jentle","age":18,"height":182.5,"age":19}
    v = dict.items()
    print(type(v))#<class 'dict_items'>
    print(v)#dict_items([('name', 'Jentle'), ('age', 19), ('height', 182.5)])
    #遍历
    for key,value in dict.items():
        print(key,":\t",value)
    '''
    name :   Jentle
    age :    19
    height :     182.5
    '''
    dict2 = {"weight":75,"address":"北京"}
    dict.update(dict2)#方法没有任何返回值
    print(dict)#{'name': 'Jentle', 'age': 19, 'height': 182.5, 'weight': 75, 'address': '北京'}
    
    #删除字典给定键 key 所对应的值,返回值为被删除的值。
    popObj = dict.pop("address")
    print(popObj)#北京
    
    

    6. 字典的遍历

    字典支持for循环遍历,直接遍历字典得到的为字典的key

    dict = {"a":"A","b":"B","c":"C"}
    for i in dict:
        print(i)
    #output:
    a
    b
    c
    

    当然也可以通过for循环遍历字典的items来遍历键值对

    for key,value in dict.items():
        print(key,value)
    #output:
    a A
    b B
    c C
    

    相关文章

      网友评论

          本文标题:009.Python字典

          本文链接:https://www.haomeiwen.com/subject/rkyxmftx.html