#增加字典值
方法一:
massage = {"name":wade,"age":30,"hobby":["girl","book","money"]}
massage["work"]="程序猿"
print(massage)
方法二:
dict1 = massage.setdefault("work","程序猿")
print(dict1)
#该方法拥有返回值!
#当增加的元素key值存在时,返回值为原始值
dict1 = massage.setdefault("name","james")
print(dict1) #返回值为wade
#当增加的元素可以值不存在时,返回值为value
dict1 = massage.setdefault("city","XIAN")
print(dict1) #返回值为XIAN
#查
massage = {"name":wade,"age":30,"hobby":["girl","book","money"]}
dic1 = massage["name"] #通过键查找
dic2 = massage.keys() #查看所有的键,该方法返回的是一个列表键类型的数据,如需使用必须转换成list类型
print(list(massage.keys()))
dic3 = massage.values() #查看所有的值
print(dic3)
dic4 = massage.items() #查看所有的键值对,结果以列表形式返回,列表内的键值对以元祖形式存储
print(dic4)
#改
massage = {"name":wade,"age":30,"hobby":["girl","book","money"]}
massage["name"] = "James"
massage2 = {"address":"XIAN","work":"IT","age":29}
massage.update(massage2) #将massage2中数据加入到massage中,若有重复数据,则覆盖massage中的数据
print(massage)
#删
massage = {"name":wade,"age":30,"hobby":["girl","book","money"]}
del massage #删除字典
del(massage["name"]) #删除指定的键值对
massage.clear() #清空列表
massage.pop("name") #有返回值,返回值为成功删除的值
massage.popitem() #随机删除一组键值对
#排序 按照键的数序(ASCII码)排列
dic = {5:"555",2:"666",4:"44"}
print(sorted(dic))
for循环遍历
dic1 = {"name":"wade","age":18,"address":"xian"}
for i in dic1
print(i,dic1[i])
获取字典的所有key
dic = {5:"555",2:"666",4:"44"}
keys = dic.keys()
print(type(keys))
注:此处获得的key并非列表,而是<class 'dict_keys'>类型,如需获取其中值必须使用list()方法强转