字典的基本用法
user_info={"name":"wang","age":"26","gender":"man"} #我们用键值对来表示 key:name,age,gender value:wang,26,man
#清空字典
user_info={"name":"wang","age":"26","gender":"man"} user_info.clear() print(user_info) #输出:{}
# 通过键获得值
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.get("name") print(str1) #输出:wang
# 获得字典里面内容以列表表示
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.items() print(str1) #输出:dict_items([('name', 'wang'), ('gender', 'man'), ('age', '26')])
#获得字典里面所有键值 列表表示
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.keys() print(str1) #输出:dict_keys(['name', 'gender', 'age'])
#获得字典里面所有的键值表示
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.values() print(str1) #输出:dict_values(['26', 'wang', 'man'])
#增加
user_info={"name":"wang","age":"26","gender":"man"} user_info["salary"]="2000" print(user_info)
#{'name': 'wang', 'age': '26', 'gender': 'man', 'salary': '2000'}
#查找
user_info={"name":"wang","age":"26","gender":"man"} print("age" in user_info.keys()) #输出:True
#删除
user_info={"name":"wang","age":"26","gender":"man"} ret=user_info.pop("name") print(ret)
#返回 wang 有放回值
dic={"k1":11,"k2":22,"k3":33} del dic["k2"] print(dic) #输出{'k1': 11, 'k3': 33} 无返回值 #如果删除的key不在字典中那么就会报错 dic={"k1":11,"k2":22,"k3":33} del dic["k5"] print(dic) #输出:KeyError: 'k5'
update(self, E=None, **F): 更新字典(个人感觉没什么卵用)
dic={"k1":11,"k2":22,"k3":33} dic.update({"k1":11,"k2":22,"k3":33,"k4":55}) print(dic) #输出:{'k2': 22, 'k4': 55, 'k3': 33, 'k1': 11}