python字典的常用方法
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.keys())
print(type(dct.keys()))
dict_keys(['name', 'age', 'gender', 'hobby'])
<class 'dict_keys'>
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.values())
print(type(dct.values()))
dict_values(['zhangsan', 12, 'man', 'play game'])
<class 'dict_values'>
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.items())
dict_items([('name', 'zhangsan'), ('age', 12), ('gender', 'man'), ('hobby', 'play game')])
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.get("name"))
zhangsan
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.pop("name"))
print(dct)
zhangsan
{'age': 12, 'gender': 'man', 'hobby': 'play game'}
- popitem:删除最后一个键,返回值是删除的键值对
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.popitem())
print(dct)
('hobby', 'play game')
{'name': 'zhangsan', 'age': 12, 'gender': 'man'}
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.clear())
print(dct)
None
{}
- setdefault:如果指定的键存在,那么直接返回键对应的值,如果指定的键不存在,那么就会添加键,并且第二个参数作为键的值
dct = { "name":"zhangsan", "age":12, "gender":"man", "hobby":"play game" }
print(dct.setdefault("name","lisi"))
print(dct)
print(dct.setdefault("job","student"))
print(dct)
zhangsan
{'name': 'zhangsan', 'age': 12, 'gender': 'man', 'hobby': 'play game'}
student
{'name': 'zhangsan', 'age': 12, 'gender': 'man', 'hobby': 'play game', 'job': 'student'}