Python之字典(dict)基本用法
创建字典
user_info={"name":"wang","age":"26","gender":"man"}
#我们用键值对来表示
key:name,age,gender
value:wang,26,man
clear(self) 移除字典中所有的元素
user_info={"name":"wang","age":"26","gender":"man"} user_info.clear() print(user_info) #输出:{}
get(self, k, d=None) 根据k返回字典中所对应的值
user_info={"name":"wang","age":"26","gender":"man"}
str1= user_info.get("name")
print(str1)
#输出:wang
items(self) 返回字典中所有的键值对
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.items() print(str1)
#输出:dict_items([('name', 'wang'), ('gender', 'man'), ('age', '26')])
keys(self) 返回字典中所有的key
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.keys() print(str1) #输出:dict_keys(['name', 'gender', 'age'])
values(self) 返回字典中所有的value
user_info={"name":"wang","age":"26","gender":"man"} str1= user_info.values() print(str1) #输出:dict_values(['26', 'wang', 'man'])
in 可见检查指定key是否在字典中
user_info={"name":"wang","age":"26","gender":"man"} print("age" in user_info.keys())
#输出:True