#遍历字典中的键 for x in thisdict: print(x) #遍历字典中的值 for x in thisdict: print(thisdict[x]) #使用values()函数返回字典中的值 for x in thisdict.values(): print(x) #使用items()函数遍历键值对 for x,y in thisdict.items(): print(x,y)
功能
同样的,可以在字典中使用in来检查键是否存在与字典中
可以通过len()函数确定字典的长度(键值对)作为参数
1 2 3 4
if"name"in thisdict: print("yes")
print(len(thisdict))
字典的增删改
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#通过方括号的方式对键的值进行更改 thisdict["name"] = "White" #通过新的键和值来对字典项目进行新增 thisdict["No."] = "15948060069" #使用内建函数pop()删除指定键的项目 thisdict.pop("No.") #使用内建函数popitem()删除最后插入的项目(在3.7之前的版本中,删除随机项目) thisdict.popitem() #使用del关键字删除指定键的项目 del thisdict["name"] #使用del完全删除字典 del thisdict #使用clear()内建函数清空字典 thisdict.clear()