• 字典类型内置方法


    字典类型内置方法

    用途

    存多个值,但每一个值都有一个key与之对应,不通过索引取值,可以通过key值进行取值

    定义

    { }可以存多个元素,每个元素中间用逗号隔开,元素通过key:value的形式存在

    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    info_dict1 = dict({'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'})
    print(info_dict)
    print(info_dict1)
    
    {'name': 'hades', 'weight': 125, 'height': 167.6, 'hobby': 'read'}
    {'name': 'hades', 'weight': 125, 'height': 167.6, 'hobby': 'read'}
    

    常用操作+内置方法

    优先掌握

    按key存取值:可存可取

    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    
    print(info_dict)
    print(info_dict['name'])
    
    {'name': 'hades', 'weight': 125, 'height': 167.6, 'hobby': 'read'}
    hades
    

    长度len

    语法:len(dict)

    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    
    print(len(info_dict))
    
    4
    

    成员运算in和not in

    语法:只能匹配key值,不能匹配value值

    • print(object in dict)
    • print(object not in dict)
    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    
    print('name' in info_dict)
    print('125' in info_dict)
    
    True
    False
    

    删除del

    语法:del dict[key]

    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    print(info_dict)
    
    del info_dict['height']
    print(info_dict)
    
    {'name': 'hades', 'weight': 125, 'height': 167.6, 'hobby': 'read'}
    {'name': 'hades', 'weight': 125, 'hobby': 'read'}
    

    键keys()、值values()、键值对items()

    语法:

    • dict.keys() 取出字典的key值
    • dict.values()取出字典的value值
    • dict.items()取出字典的key和value值
    info_dict = {'name': 'hades',
                 'weight': 125,
                 'height': 167.6,
                 'hobby_list': ['read', 'write', 'listen music', 'travel']}
    
    print(info_dict.keys())
    print(info_dict.values())
    print(info_dict.items())     # 取出的值为元组
    
    dict_keys(['name', 'weight', 'height', 'hobby_list'])
    dict_values(['hades', 125, 167.6, ['read', 'write', 'listen music', 'travel']])
    dict_items([('name', 'hades'), ('weight', 125), ('height', 167.6), ('hobby_list', ['read', 'write', 'listen music', 'travel'])])
    

    循环

    语法:

    • for k,v in dict.items()
    • for k in dict.keys()
    • for v in dict.values()
    info_dict = {'name': 'hades',
                 'weight': 125,
                 'height': 167.6,
                 'hobby_list': ['read', 'write', 'listen music', 'travel']}
    for k,v in info_dict.items():
        print(k,v)
    print()
    
    for k in info_dict.keys():
        print(k)
    print()
    
    for v in info_dict.values():
        print(v)
    
    name hades
    weight 125
    height 167.6
    hobby_list ['read', 'write', 'listen music', 'travel']
    
    name
    weight
    height
    hobby_list
    
    hades
    125
    167.6
    ['read', 'write', 'listen music', 'travel']
    

    需要掌握

    get

    语法:dict.get('key')获取字典中对应key的value值

    info_dict = {'name': 'hades','weight': 125,'height': 167.6,'hobby': 'read'}
    
    print(info_dict.get('weight'))
    print(info_dict.get('hades'))
    
    125
    None
    

    update

    语法:dict.update(dict1)更新,如果有相同的key,则会更新;如果没有相同的key,则会添加进去。

    info_dict = {'name': 'hades','weight': 125,'hobby': 'read'}
    dic1 = {'name':'bonnie'}
    dic2 = {'height': 167.6}
    
    info_dict.update(dic1) # 更新value值
    print(info_dict)
    
    info_dict.update(dic2) # 添加,添加到最后
    print(info_dict)
    
    {'name': 'bonnie', 'weight': 125, 'hobby': 'read'}
    {'name': 'bonnie', 'weight': 125, 'hobby': 'read', 'height': 167.6}
    

    fromkeys

    语法:dict.fromkeys(s,value)用于创建一个新字典,以序列s(集合,列表,字符串,元组)中元素做字典的键,value为字典所有键对应的初始值

    str1 = '124'
    lis = ['1','2','4']
    set1 = {'1','2','4'}
    tup = ('1','2','4')
    
    print(dict.fromkeys(str1,None))
    print(dict.fromkeys(lis,'name'))
    print(dict.fromkeys(set1,'weight'))
    print(dict.fromkeys(tup,'height'))
    
    {'1': None, '2': None, '4': None}
    {'1': 'name', '2': 'name', '4': 'name'}
    {'2': 'weight', '4': 'weight', '1': 'weight'}
    {'1': 'height', '2': 'height', '4': 'height'}
    
    a= 124
    print(dict.fromkeys(a,None))   # 报错,因为数值类型是无序的
    
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-18-0a988029f394> in <module>
          1 a= 124
    ----> 2 print(dict.fromkeys(a,None))   # 报错,因为数值类型是无序的
    
    
    TypeError: 'int' object is not iterable
    

    setdefault

    语法;dict.setdefault(key, default=None)如果key在字典里,不做任何修改;如果key不在字典里面,添加值default,默认为None

    info_dict = {'name': 'hades','weight': 125,'hobby': 'read'}
    
    info_dict.setdefault('name',3)    #  key值存在,不做任何改变
    print(info_dict)
    
    {'name': 'hades', 'weight': 125, 'hobby': 'read'}
    
    info_dict = {'name': 'hades','weight': 125,'hobby': 'read'}
    
    info_dict.setdefault('food')        # 默认为None
    print(info_dict)
    
    info_dict.setdefault('height',168.4)    #  key值不存在,添加进去
    print(info_dict)
    
    {'name': 'hades', 'weight': 125, 'hobby': 'read', 'food': None}
    {'name': 'hades', 'weight': 125, 'hobby': 'read', 'food': None, 'height': 168.4}
    

    存一个值or多个值

    多个值,value值可变任意类型,key必须是不可变类型

    有序or无序

    无须

    可变or不可变

    可变数据类型

    练习

    • 统计s='hello jason tank tank jason sean say hello dsb dsb sb'中每个单词的个数,结果为{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
    s='hello jason tank tank jason sean say hello dsb dsb sb'
    lis = s.split()
    dic = {}
    for i in lis:
        if i not in dic:
            dic[i] = 1
        else:
            dic[i] += 1
    print(dic)
    
    {'hello': 2, 'jason': 2, 'tank': 2, 'sean': 1, 'say': 1, 'dsb': 2, 'sb': 1}
  • 相关阅读:
    数据结构最小生成树两个算法
    hdu-1742Ellipse(自适应辛普森)
    hdu1251统计难题
    codeforces-551C GukiZ hates Boxes
    CodeForces
    codeforces-894C Marco and GCD Sequence
    codeforces-892B Wrath
    codeforces-894B Ralph And His Magic Field
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/Hades123/p/10839345.html
Copyright © 2020-2023  润新知