Python之路—Day4

字典的操作:

一.增加

1 >>> student_num = {"stu1101": "阿橙", "stu1102": "阿万", "stu1103": "阿朝", "stu1104": "peter1",}
2 >>> student_num["stu1105"] = "zebra"     #增加
3 >>> print(student_num)
4 {'stu1101': '阿橙', 'stu1102': '阿万', 'stu1103': '阿朝', 'stu1104': 'peter1', 'stu1105': 'zebra'}
5 >>>

二.修改

1 >>> student_num = {"stu1101": "阿橙", "stu1102": "阿万", "stu1103": "阿朝", "stu1104": "peter1",}
2 >>> student_num["stu1101"] = "gkx"  #修改
3 >>> student_num
4 {'stu1101': 'gkx', 'stu1102': '阿万', 'stu1103': '阿朝', 'stu1104': 'peter1', 'stu1105': 'zebra'}

三.删除

 1 >>> #删除
 2 >>> student_num.pop("stu1104")   #标准删除方法
 3 'peter1'
 4 >>> student_num
 5 {'stu1101': 'gkx', 'stu1102': '阿万', 'stu1103': '阿朝', 'stu1105': 'zebra'}
 6 >>> 
 7 >>> 
 8 >>> del student_num["stu1105"]
 9 >>> student_num
10 {'stu1101': 'gkx', 'stu1102': '阿万', 'stu1103': '阿朝'}
11 >>> #ptyhon内置的删除方法
12 >>> 
13 >>> student_num.popitem()  #随机删除
14 ('stu1103', '阿朝')
15 >>> student_num
16 {'stu1101': 'gkx', 'stu1102': '阿万'}
17 >>> 

四.查找

 1 >>> #查找
 2 >>> zoo = {"a101":"zebra","b202":"chimpanzee","c303":"lion"}
 3 >>> "a101" in zoo  #判断字典中key是否在dict中
 4 True
 5 >>> 
 6 >>> zoo["a101"]
 7 'zebra'
 8 >>> #用key来查找value,不过当key不在该dict中时,会报错
 9 >>> 
10 >>> zoo.get("d404")
11 >>> print(zoo.get("d404"))
12 None
13 >>> print(zoo.get("c303"))
14 lion
15 >>> #用.get的方法,找不到不会报错,建议使用

五.字典的循环和自动生成

 
 

  >>> zoo.values()  #打印所有value
  dict_values(['zebra', 'chimpanzee', 'lion'])
  >>> zoo.keys()    #打印所有key
  dict_keys(['a101', 'b202', 'c303'])

 1 >>> zoo2
 2 {'c303': 'lion', 'd404': 'elephant', 'c4': 'tiger'}
 3 >>> for key in zoo2:           #打印key和value
 4     print(key,zoo2[key])
 5 
 6 >>>
 7 c303 lion
 8 d404 elephant
 9 c4 tiger
10 >>> 
11 
12 >>> for k,v in zoo2.items():  #数据量大时不要用
13     print(k,v)
14 
15 >>>    
16 c303 lion
17 d404 elephant
18 c4 tiger
19 >>> 
20 
21 >>> dict.fromkeys([1,2,3],4)  #了解这个知识点就好,慎用
22           
23 {1: 4, 2: 4, 3: 4}

六.字典的其他操作

 1 >>> #setdefault
 2 >>> zoo2 = {"a101":"zebra","b202":"chimpanzee","c303":"lion"}
 3 >>> zoo2.setdefault("a101","cat")  #setdefault 判断key是否在dict中,若在则不做修改,若不在则将新key添加至dict中
 4 'zebra'
 5 >>> zoo2
 6 {'a101': 'zebra', 'b202': 'chimpanzee', 'c303': 'lion'}
 7 >>> zoo2.setdefault("d404","elephant")
 8 'elephant'
 9 >>> zoo2
10 {'a101': 'zebra', 'b202': 'chimpanzee', 'c303': 'lion', 'd404': 'elephant'}
11 >>> 
12 
13 >>> zoo2
14 {'c303': 'lion', 'd404': 'elephant'}
15 >>> dict_b = {1:2,2:3,"c4":"tiger"}
16 >>> zoo2.update(dict_b)  #类似列表中的extend
17 >>> zoo2
18 {'c303': 'lion', 'd404': 'elephant', 1: 2, 2: 3, 'c4': 'tiger'}
19 
20 >>> #items
21 >>> zoo2.items()    #将字典中的key、value值对,一对对拿出,生成为新列表
22 dict_items([('c303', 'lion'), ('d404', 'elephant'), (1, 2), (2, 3), ('c4', 'tiger')])
23 >>> 

 

猜你喜欢

转载自www.cnblogs.com/gkx0731/p/9425169.html