Python-字典Dict

mac2022-06-30  17

字典(Dictionary)

  键必须不可变,所以可以用数字,字符串或元组充当,列表不行

字典的遍历

  1、遍历Key

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 for i in dict1: 3 print(i)    #输出如下红球篮球黄球

   

     (- 如果每个Key同样位数,能将Key每个字符分开。)

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 for i,b in dict1: 3 print(i,":“,b)  #输出如下:红 : 球篮 : 球黄 : 球

  

  2、遍历values

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 for i in dict1.values(): 3 print(i)  #输出如下:534

  

  3、遍历字典项。【得到tuple类型】

 

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 for i in dict1.items(): 3 print(i) 4 print(type(i))  输出如下:('红球', 5)('篮球', 3)('黄球', 4)<class 'tuple'>

 

   

     (-遍历字典项的键值。)

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 for i,b in dict1.items(): 3 print(i,b) 4 print(type(i))  #输出如下:红球 5篮球 3黄球 4<class 'str'>

 

常用增减字典项方法

  增加字典项

    -dict[key] = values

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 dict1["黑球"] = 6          #方法1 dict[key] = values 3 print(dict1)  #输出如下:{'红球': 5, '篮球': 3, '黄球': 4, '黑球': 6}

    

    -dict.setdefault(key,values)

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 dict1.setdefault("黑球",7) #方法2 dict.setdefault(key,values) 3 print(dict1)   #输出如下:{'红球': 5, '篮球': 3, '黄球': 4, '黑球': 7}

   

     -update(关键字=values)、update((key,values))、update({key:values})     

      【以上都可以,输入原有的key时,新values替代旧values】

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 dict1.update(黑球=7) #没有错,黑球并没有双引号!!!!直接传关键字 3 print(dict1)  #输出如下:{'红球': 5, '篮球': 3, '黄球': 4, '黑球': 7}

 

  删除字典项

    -pop(key)

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 dict1.pop("红球") 3 print(dict1)  #输出如下:{'篮球': 3, '黄球': 4}

    

    -del dict[key] 

1 dict1 = {"红球":5,"篮球":3,"黄球":4} 2 del dict1["红球"]            #注意是中括号,不是小括号 3 print(dict1)    #输出如下:{'篮球': 3, '黄球': 4}

 

转载于:https://www.cnblogs.com/simplecat/p/11273172.html

最新回复(0)