美文网首页
python学习六

python学习六

作者: 多啦A梦的时光机_648d | 来源:发表于2020-03-23 11:50 被阅读0次

    字典

    字典的标志性符号是大括号{},属于映射类型

    1. 创建和访问字典

    • 利用映射关系创建
    dict1 = {1:'one','2':'two','3':'three','4':'four'}
    ## 这里的1就是键key, 'two'就是值value
    print(dict1[1])
    one
    print(dict1['2'])
    two
    
    • 通过dict()工厂函数创建
    dict1 = dict(我='one', 你='two', 他='three')   ##这里的key不能加引号''
    print(dict1)
    {'我': 'one', '你': 'two', '他': 'three'}
    
    • 更改key的value
    dict1['我'] = 'wo'
    {'我': 'wo', '你': 'two', '他': 'three'}
    ## 若修改的key在原来的字典里是没有的,则会添加到字典中
    
    dict1['它'] = 'four'
    print(dict1)
    {'我': 'wo', '你': 'two', '他': 'three', '它': 'four'}
    

    2.访问字典

    • keys()
    for eachkey in dict.keys():
            print(eachkey)
    
    • values()
    for eachvalue in dict.values():
            print(value)
    

    *items()

    for eachitem in dict.items():
            print(eachitem)
    

    3.清空字典

    dict.clear()
    ##不要用dict={}
    a = {'我':'wo'}
    b = a
    a = {}
    print(a)
    print(b)
    {}
    {'我':'wo'}  ##这里和列表是相反的
    
    • pop()

    给定一个键,弹出对应的值

    dict = {'我':'wo'}
    dict.pop(我)
    'wo'
    
    • popitem()

    由于字典无序,所以是随即弹出一个数据

    {'我':'wo'}
    dict.popitem()
    ('我':'wo')
    

    相关文章

      网友评论

          本文标题:python学习六

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