字典 dict
- 索引
- 长度
- for循环
user_info = {"name":3,"age":11,"country":"china"} print(user_info["country"]) print(len(user_info)) for k in user_info: print(k) china 3 name country age
- 所有的keys
- 所有的values
- 所有的keys,values
user_info = {"name":"Amy","age":11,"country":"china"} print(user_info.keys()) print(user_info.values()) print(user_info.items()) dict_keys(['country', 'age', 'name']) dict_values(['china', 11, 'Amy']) dict_items([('country', 'china'), ('age', 11), ('name', 'Amy')])
- for循环
for k,v in user_info.items(): print(k) age country name
for k,v in user_info.items(): print(v) 11 china Amy
for k,v in user_info.items(): print(k,v) name Amy country china age 11
其他方法:
- 1、clear
user_info = {"name":"Amy","age":11,"country":"china"} user_info.clear() print(user_info) {}
- 2、copy
- 3、get 获取一个不存在key,get返回none,如果通过索引获取一个不存在的key,则报错;
user_info = {"name":"Amy","age":11,"country":"china"} print(user_info.get("age")) print(user_info.get("sss")) 11 None