1. 字典的创建
1 # 1. 创建 2 # 用{}创建 3 s1 = {'a':'s','b':1} 4 print(s1) 5 # 用内置函数dict创建 6 s2 = dict(a="s",b=1) 7 s3 = dict((('a','s'),('b',1))) # 元组内元组 8 s4 = dict((['a','s'],['b',1])) # 元组内列表 9 s5 = dict([('a','s'),('b',1)]) # 列表内元组 10 s6 = dict([['a','s'],['b',1]]) # 列表内列表 11 print(s2) 12 print(s3) 13 print(s4) 14 print(s5) 15 print(s6) 16 # 用dict.fromkeys方法创建 17 s7 = dict.fromkeys(('a','b','c'),1) 18 s8 = dict.fromkeys(['a','b','c'],2) 19 print(s7) 20 print(s8)
2. 字典的增删改查,遍历
1 # 2. 增删改查 2 ''' 3 # 增 4 s = {'a':1,'b':2} 5 s.update(c=3,f=12) 6 s.update({'d':4,'g':'s'}) 7 s['e'] = 5 8 s.setdefault('x',100) 9 s.setdefault('x',1000) # key(x)不存在则添加,如果key(x)存在则返回value 10 print(s) 11 ''' 12 ''' 13 # 删 14 s = {'a': 1, 'b': 2, 'c': 3, 'f': 12, 'd': 4, 'g': 's', 'e': 5} 15 a = s.pop('a') # 删除键值对,将值赋给变量a 16 print(a) 17 print(s) 18 del s["b"] 19 print(s) 20 ''' 21 ''' 22 # 改 23 s = {'a':1,'b':2} 24 s['a'] = 10 # key存在则修改value,key不存在则添加 25 print(s) 26 print(s) 27 ''' 28 ''' 29 # 查 30 s = {'a': 1, 'b': 2, 'c': 3, 'f': 12, 'd': 4, 'g': 's', 'e': 5} 31 print(s['a']) 32 print(s['f']) 33 print(s.keys()) # 可通过list或tuple转换为列表或元组 34 print(s.values()) 35 print(s.items()) 36 ''' 37 # 遍历 38 s = {'a': 1, 'b': 2, 'c': 3, 'f': 12, 'd': 4, 'g': 's', 'e': 5} 39 for key,value in s.items(): 40 print(key+"_____"+str(value)) 41 42 for key in s.keys(): 43 print(key) 44 45 for value in s.values(): 46 print(value) 47 48 for key in s.keys(): 49 print(key + "_____" + str(s[key]))