标签:访问 查找 key值 清空 color 函数 style 说明 key
说明:字典是可变容器,可以存储任何类型对象,使用键-值(key-value)存储,具有极快的查找速度。键是唯一的,值可以取任何数据类型
dict={} #创建空字典
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘} print ("dict[‘Name‘]=",dict[‘Name‘]) print ("dict[‘Age‘]=",dict[‘Age‘])
运行结果:
dict[‘Name‘]= Zara
dict[‘Age‘]= 7
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘} dict[‘Age‘]=8 #修改键的值 print ("dict[‘Age‘]=",dict[‘Age‘]) dict[‘school‘]=‘XINDONGFANG‘ #增加新的键值 print (dict)
运行结果:
dict[‘Age‘]= 8
{‘Name‘: ‘Zara‘, ‘Age‘: 8, ‘Class‘: ‘First‘, ‘school‘: ‘XINDONGFANG‘}
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘} del dict[‘Name‘] #删除字典元素 print (dict) dict.clear() #清除字典 print (dict) del dict #删除字典 print (dict)
运行结果:
{‘Age‘: 7, ‘Class‘: ‘First‘}
{}
<class ‘dict‘>
#遍历key值 for key in dict.keys(): print (key) print (‘--‘*10) #遍历value值 for value in dict.values(): print (value) print (‘--‘*10) #遍历key和value值 for key,value in dict.items(): print (key+‘=‘+str(value))
运行结果:
Name
Age
Class
--------------------
Zara
7
First
--------------------
Name=Zara
Age=7
Class=First
方法一:通过 in 判断key是否存在
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}
print (‘Name1‘ in dict)
运行结果:
False
注意:python3没有has_key()方法,用in代替
方法三:get()方法判断key是否存在,key不存在,返回None,或指定的value值
dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘}
print (dict.get(‘Name‘)) print (dict.get(‘Name2‘,-1))
运行结果:
Zara
-1
dict1 = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘} dict2=sorted(dict1) print (dict2)
运行结果:
[‘Age‘, ‘Class‘, ‘Name‘]
dict1 = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘} dict2=sorted(dict1.keys(),reverse=True) print (dict2)
dict1={‘a‘:2,‘e‘:3,‘f‘:8,‘d‘:4} list1 = sorted(dict1.values(),reverse=True) print (list1)
运行结果:
[8, 4, 3, 2]
dict1={‘a‘:2,‘e‘:3,‘f‘:8,‘d‘:4} print (dict1.items()) list1=sorted(dict1.items(),key=lambda x:x[0]) #按键key进行排序 print (list1) list2=sorted(dict1.items(),key=lambda x:x[1]) #按键value进行排序 print (list2)
运行结果:
dict_items([(‘a‘, 2), (‘e‘, 3), (‘f‘, 8), (‘d‘, 4)])
[(‘a‘, 2), (‘d‘, 4), (‘e‘, 3), (‘f‘, 8)]
[(‘a‘, 2), (‘e‘, 3), (‘d‘, 4), (‘f‘, 8)]
标签:访问 查找 key值 清空 color 函数 style 说明 key
原文地址:https://www.cnblogs.com/wenxiacui/p/10964428.html