Python 字典
Python 字典 1. 遍历字典 遍历字典的键 dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key in dict1.keys(): print(key) # 输出:a b c d 遍历字典的值 dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for value in dict1.values(): print(value) dict1.get('a') dict1.get('b') dict1.get('c') # 输出:1 2 3 4 遍历字典的键值对 dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for k, v in dict1.items(): print(k, ": ", v) # 输出: a : 1 b : 2 c : 3 d : 4 更新字典 dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} dict2 = {'e': 5} dict1.update(dict2) print(dict1) # 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 删除字典所有键值对 dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} dict1.clear