字典
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,3.6版本之后字典是有序的(3.5版本之前字典是无序的),且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,3.6版本之后字典是有序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
增:setdefault

1 dic = { 2 'name':'烟雨江南', 3 'age':18, 4 'sex':'man' 5 } 6 增 7 dic['hobby'] = '看书' # 有则修改,无则添加 8 print(dic) 9 dic.setdefault('hobby','玩游戏') # 有则不变,无则添加 10 print(dic)
删:pop、clear、popitem、del

1 dic = { 2 'name':'烟雨江南', 3 'age':18, 4 'sex':'man' 5 } 6 ret = dic.pop('name') # 按照键删除键值对,并返回删除的值 7 ret = dic.pop('name1','删除的对象不存在') # 设置两个参数,第二个参数是提示语,一般设置为None;键不存在也不会报错 8 print(ret) 9 dic.clear() # 清空字典 10 dic.popitem() #3.6版本之后删除最后一个键值对 11 print(dic) 12 del dic['name'] # 按照建删除 13 print(dic)
改:update

1 dic = { 2 'name':'烟雨江南', 3 'age':18, 4 'sex':'man' 5 } 6 dic['name'] = 'jj' 7 print(dic) 8 dic.update(name = 'TSL',money=10000) #更新:有则覆盖,没有则添加 9 print(dic) 10 11 12 dic = {"name": "jin", "age": 18, "sex": "male"} 13 dic2 = {"name": "alex", "weight": 75} 14 dic2.update(dic) 15 # 将dic里面的键值对覆盖添加到dic2中
查:

1 dic = { 2 'name':'烟雨江南', 3 'age':18, 4 'sex':'man' 5 } 6 print(dic['age']) # 若不存在会报错 7 8 dic.get('age') # 没有此键默认返回None 9 print(dic) 10 ret = dic.get('age1','此键不存在') # 键不存在,可设置提示语 11 print(ret)
字典的其他操作:

1 dic = { 2 'name': '太白金星', 3 'age': 18, 4 'hobby': 'wife', 5 } 6 # 查看键 7 res = dic.keys() # 查看字典中所有键 8 print(res,type(res)) # <class 'dict_keys'> 该类型可以循环遍历 9 for i in res: 10 print(i) 11 print(list(res)) # 也可以通过list转化为列表 12 ------------------------------------------------------------- 13 # 查看值 14 res1 = dic.values() # 查看字典中所有值 15 print(res1,type(res1)) # <class 'dict_values'> 该类型可以循环遍历 16 for i in res1: 17 print(i) 18 print(list(res1)) # 也可以通过list转化为列表 19 ------------------------------------------------------------- 20 #查看键值对 21 res2 = dic.items() 22 print(res2,type(res2)) # 查看字典中所有键值对 23 for i in res2: 24 print(i) 25 print(list(res2)) # 也可通过list转化为列表:[('name', '太白金星'), ('age', 18), ('hobby', 'wife')]
小练习:

1 dic = { 2 'name_list': ['博哥', '菊哥', 'b哥', 'alex'], 3 'barry': { 4 'name': '太白金星', 5 'age': 18, 6 'hobby': 'wife', 7 } 8 } 9 1,给这个列表['博哥', '菊哥', 'b哥', 'alex'] 追加一个元素 '老男孩'。 10 2,将这个列表['博哥', '菊哥', 'b哥', 'alex']中的alex变成首字母大写。 11 3,将这个键值对 'name': '太白金星' 的 '太白金星' 改成男神。 12 4,给barry对应的小字典增加一个键值对: weight: 160 13 14 dic.get('name_list').append('老男孩') 15 dic['name_list'][3]= dic['name_list'][3].capitalize() 16 dic['barry']['name'] = '男神' 17 dic['barry'].setdefault('weight',160) 18 dic['barry'].update(weight = 160) 19 print(dic)
面试题:

1 ''' 2 a = 18 3 b = 32 4 通过一行代码 将a,b的值互换。 5 6 ''' 7 a = 18 8 b = 32 9 a, b = b, a