一:字典(dic)
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
1.增
dic = {"name":"jin","age":18,"sex":"male"} # dic[‘key‘] = ‘value‘ key存在则改变,key不存在则添加 dic[‘name‘] = ‘qwe‘ print(dic) dic[‘hobby‘] = ‘旅游‘ print(dic) # 输出结果:{‘name‘: ‘qwe‘, ‘age‘: 18, ‘sex‘: ‘male‘, ‘key‘: ‘value‘} # 输出结果:{‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘, ‘hobby‘: ‘旅游‘} # setdefault key存在不变,不存在则添加 dic.setdefault(‘age‘,‘15‘) print(dic) dic.setdefault(‘hobby‘,‘旅游‘) print(dic) # 输出结果: # {‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘} # {‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘, ‘hobby‘: ‘旅游‘}
2.删
dic = {"name":"jin","age":18,"sex":"male"} # pop 按key删除,有返回值 如果没有key,可设置返回值(不设置返回值报错) dic.pop(‘name‘) print(dic) # 输出结果: # {‘age‘: 18, ‘sex‘: ‘male‘} ret = dic.pop(‘hobby‘,‘没有此键‘) print(ret) print(dic) # 输出结果: # 没有此键 # {‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘} # clear 清空字典 dic.clear() print(dic) # 输出结果:{} del 删除字典,删除键值对 del dic 删除字典 del dic[‘name‘] print(dic) # 输出结果: # {‘age‘: 18, ‘sex‘: ‘male‘} popitem 随机删除 ret = dic.popitem() print(ret) print(dic) # 输出结果: # (‘sex‘, ‘male‘) # {‘name‘: ‘jin‘, ‘age‘: 18}
3.改
dic = {"name":"jin","age":18,"sex":"male"} dic2 = {"name":"alex","weight":75} # dic[‘key‘] = ‘value‘ 有 key 就覆盖,没有就添加 # update 把dic2中的 键值对 覆盖添加 到dic中,dic 不变 dic.update(dic2) print(dic) # 输出结果: # {‘name‘: ‘alex‘, ‘age‘: 18, ‘sex‘: ‘male‘, ‘weight‘: 75}
4.查
dic = {"name":"jin","age":18,"sex":"male"} print(dic[‘name‘]) #通过 key 直接查 value 没有 key 报错 print(dic[‘age‘]) print(dic[‘name‘],type(dic[‘name‘])) print(dic[‘age‘],type(dic[‘age‘])) # 输出结果: # jin <class ‘str‘> # 18 <class ‘int‘> # get 通过 key 直接查 value 没有 key 时,可设置返回值 print(dic.get(‘name‘)) print(dic.get(‘name1‘)) print(dic.get(‘name1‘,‘没有此键对‘)) # 输出结果: # jin # None # 没有此键对
5.字典的其他方法
dic = {"name":"jin","age":18,"sex":"male"} keys = dic.keys() print(keys,type(keys)) # 输出结果: # dict_keys([‘name‘, ‘age‘, ‘sex‘]) <class ‘dict_keys‘> values = dic.values() print(values) # 输出结果: # dict_values([‘jin‘, 18, ‘male‘]) items = dic.items() print(items) # 输出结果: # dict_items([(‘name‘, ‘jin‘), (‘age‘, 18), (‘sex‘, ‘male‘)]) for k in dic: print(k) ‘‘‘ 输出结果: name age sex ‘‘‘ for v in dic: print(v) ‘‘‘ # 输出结果: name age sex ‘‘‘ for k,v in dic.items(): print(k,v) ‘‘‘ # 输出结果: name jin age 18 sex male ‘‘‘ for k in dic: print(k,dic[k]) ‘‘‘ # 输出结果: name jin age 18 sex male ‘‘‘
6,字典的嵌套
dic = { ‘name‘: "金鑫", ‘name_list‘:[1, 2, 3, ‘李杰‘], 1: { ‘python10‘:[‘小黑‘, ‘萌哥‘], ‘老男孩‘: {‘name‘:‘oldboy‘, ‘age‘:56} } } #1,[1,2,3,‘李杰‘]追加‘wusir‘ dic[‘name_list‘].append(‘wusir‘) print(dic) #2, [‘小黑‘,‘萌哥‘] 小黑 萌哥中间 插入一个花哥 dic[1][‘python10‘].insert(1,‘花哥‘) print(dic) #3, {‘name‘:‘oldboy‘,‘age‘:56} 添加一个键值对,hobby:男人 dic[1][‘老男孩‘][‘hobby‘] = ‘男人‘ print(dic) dic[1][‘老男孩‘].setdefault(‘hobby‘,‘男人‘) print(dic)