zoukankan      html  css  js  c++  java
  • python之字典

    字典(dictionary):字典的定义使用{},大括号,每个值用“,”隔开,key和value使用“:”分隔。

    dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}

    字典的特性:
    字典是无序的,因为它没有下标,用key来当索引,所以是无序的
    字典的key必须是唯一的,因为它是通过key来进行索引的,所以key不能重复,天生就去重

    字典的一些操作

    增加元素

    1 dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}
    2 
    3 dict1['rose'] = [21, 'England']

    修改元素

    dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}
    
    dict1['tom'] = [14, 'Amercia']

    删除元素

    1 dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}
    
    2 dict1.pop('jerry') #删除指定元素
    
    3 del dict1('jerry')  #使用del方法删除

    查询元素

    1 dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}
    2 
    3 print(dict1.get('jack')) #这种方式如果key不存在的话,会返回None
    4 
    5 print(dict['jack'])        #这种方式如果key不存在的话,会报错
    6 
    7 print('jack' in dict1)    #判断jack是否在这个字典中,返回True或者False

    内置方法

     1 dict1 = {'tom': [12, 'Amercia'], 'jerry': [11, 'Amercia'] ,'jack': [20, 'England']}
     2 
     3 print(dict1.keys())       #打印所有key
     4 
     5 print(dict1.values())    #打印所有value
     6 
     7 print(dict1.setdefault.('judy',[20,'England']))  #如果key存在,不动,不存在,添加
     8 
     9 dict2 = {'john': [24, 'russia']}
    10 
    11 dict1.update(dict2)  #更新字典,如果key存在,更新;不存在,添加

    12 print(dict1.items()) #转变成列表
  • 相关阅读:
    FFT入门
    FJOI省队集训 chessboard
    FJOI省队集训 florida
    树上莫队
    NOIP2015 Revenge
    APIO2013 tasksauthor
    油漆门
    一些字符串有关的题目
    字符串题模板集合
    sg函数与博弈论2
  • 原文地址:https://www.cnblogs.com/wuxiaoyu-1537/p/7363117.html
Copyright © 2011-2022 走看看