字典即为放在花括号{}中一系列键值对的集合,值可以使数字、字符、集合等。
字典创建
>>> employee_1 = {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 9999} >>> >>> type(employee_1) <class 'dict'>
访问字典中的数据
>>> print(employee_1) {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 9999} >>> >>> print(employee_1['name']) david >>> >>> print("Welcome our new colleague: " + employee_1['name'] + ", " + "His post is: " + employee_1['post'] + ".") Welcome our new colleague: david, His post is: NOC.
修改字典中的数据
>>> print(employee_1) {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 9999} >>> >>> employee_1['salary'] = 12000 >>> >>> employee_1 {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000}
向字典中添加新的键值对
>>> employee_1 {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000} >>> >>> employee_1['id'] = 113 >>> >>> employee_1 {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000, 'id': 113}
删除一个键值对
>>> employee_1 {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000, 'id': 113} >>> >>> del employee_1['id'] >>> >>> employee_1 {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000}
遍历字典
遍历字典中的键值对
employee_1 = {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000, 'id': 113} for key, value in employee_1.items(): print("\nkey: %s" % key) print("value: %s" % value)
输出
key: name value: david key: dept value: ops key: post value: NOC key: salary value: 12000 key: id value: 113
遍历字典中的键
employee_1 = {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000, 'id': 113} for key in employee_1.keys(): print("key: %s" % key)
输出
key: name key: dept key: post key: salary key: id
遍历字典中的值
employee_1 = {'name': 'david', 'dept': 'ops', 'post': 'NOC', 'salary': 12000, 'id': 113} for value in employee_1.values(): print("key: %s" % value)
输出
key: david key: ops key: NOC key: 12000 key: 113
===================来自一泽涟漪的博客,转载请标明出处 www.cnblogs.com/ilifeilong===================