Python 字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
dic = {'name':'jin','age':18,'sex':'male'} print(dic)#{'name': 'jin', 'sex': 'male', 'age': 18}
####增####
#增 ##第一种:有则覆盖,无则添加 # dic = {'name':'jin','age':18,'sex':'male'} # dic['hobby'] = 'girl' # print(dic) #输出{'age': 18, 'hobby': 'girl', 'sex': 'male', 'name': 'jin'} # dic['name'] = 'wusir' # print(dic) #{'age': 18, 'sex': 'male', 'name': 'wusir'} # ##第二种:serdefult 无则添加,有则不变 dic = {'name':'jin','age':18,'sex':'male'} # dic.setdefault('hobby') # print(dic)#{'sex': 'male', 'hobby': None, 'age': 18, 'name': 'jin'} #'hobby'是键,而不是值,所以字典里会出现'hobby':None # dic.setdefault('hobby','girl') # print(dic)#{'name': 'jin', 'hobby': 'girl', 'age': 18, 'sex': 'male'} #键值对 'hobby':girl添加到字典了、原字典没有hobby # dic.setdefault('name','ritian') # print(dic)#{'age': 18, 'name': 'jin', 'sex': 'male'} #原字典中有k,name'所以不变
###删####
#pop 有返回值 # dic = {'name':'jin','age':18,'sex':'male'} # print(dic.pop('age'))##返回所删除键值对的age值18 # print(dic) # dic.pop('hobby')##报错 # print(dic.pop('hobby',None))##设定返回的键值,当hobby不存在时,返回None ##clear 清空 # dic = {'name':'jin','age':18,'sex':'male'} # dic.clear() # print(dic)#{}清空字典里面所有键值对 ##del # dic = {'name':'jin','age':18,'sex':'male'} # del dic # print(dic)#NameError: name 'dic' is not defined,通过del dic,已删除字典dic # dic = {'name':'jin','age':18,'sex':'male'} # del dic['name'] # print(dic)#{'age': 18, 'sex': 'male'},删除dic里面‘name’的键值对 # dic = {'name':'jin','age':18,'sex':'male'} # print(dic.popitem()) # print(dic)#每次随机删除dic里面的键值对
####改#####
# dic = {"name":"jin","age":18,"sex":"male"} # dic['name'] = '太白' # print(dic)#{'name': '太白', 'sex': 'male', 'age': 18}更改键name的值 # 两个字典的改 # dic = {"name":"jin","age":18,"sex":"male"} # dic2 = {"name":"alex","weight":75} # dic2.update(dic)#将dic键值对,覆盖并添加到dic2 # print(dic)#{'age': 18, 'name': 'jin', 'sex': 'male'} # print(dic2)#{'age': 18, 'sex': 'male', 'name': 'jin', 'weight': 75}
####查####
# dic = {"name":"jin","age":18,"sex":"male"} # print(dic['name'])#jin 查键所对应的值jin # print(dic['name1'])#KeyError: 'name1'如果查看没有的键,则会显示错误信息 # print(dic.get('name'))#jin # print(dic.get('name1'))#没有此键时默认返回None # print(dic.get('name1','无此键值对'))#无此键值对,后面可以设置··· ##其它方法 #key() values() item() dic = {"name":"jin","age":18,"sex":"male"} # print(dic.keys(),type(dic.keys()))#查看dic的键keys # print(dic.keys())# # for i in dic.keys(): # print(i) #列出dic的所有键 # for i in dic: # print(i) # li = list(dic.keys())#以列表的形式查看dic键 # print(li) # print(dic.values())#值 # for i in dic.values():#列出dic的键值 # print(i) # #items 随机打出dic的键值对 # print(dic.items())#打出dic的键值对,顺序随机 #dict_items([('age', 18), ('sex', 'male'), ('name', 'jin')]) # for i in dic.items():# # print(i,type(i)) # ('name', 'jin') <class 'tuple'> # ('sex', 'male') <class 'tuple'> # ('age', 18) <class 'tuple'>