学过java的同学都知道,在java中有一种键值对形式的数据格式--Map
而在Python中,有一种格式与Map类似,那就是字典(Dict)
1.创建一个字典类型对象
user={ "username":"Dylan", "age":18, "password":"123" }
2.遍历
user={ "username":"Dylan", "age":"18", "password":"123" } for k,v in user.items(): print(k+":"+v);
结果: username:Dylan
age:18
password:123
3.clear()方法--清除字典中的所有元素
user={ "username":"Dylan", "age":"18", "password":"123" } user.clear(); print(user);
结果为:{}
4.copy()复制一份到另一个字典中
user={ "username":"Dylan", "age":"18", "password":"123" } user2=user.copy(); print(user2);
结果:{‘password‘: ‘123‘, ‘username‘: ‘Dylan‘, ‘age‘: ‘18‘}
5.fromkeys():不保留源字典的值,创建一个新字典
user={ "username":"Dylan", "age":"18", "password":"123" } user2=dict.fromkeys(user); print(user2);
结果:{‘username‘: None, ‘age‘: None, ‘password‘: None}
6.get():通过键获取值
user={ "username":"Dylan", "age":"18", "password":"123" } username=user.get("username"); print(username);
结果:Dylan
7.items():得到字典的所有项(item)
user={ "username":"Dylan", "age":"18", "password":"123" } arr=user.items(); print(arr);
结果:dict_items([(‘age‘, ‘18‘), (‘username‘, ‘Dylan‘), (‘password‘, ‘123‘)])
8.keys():得到所有键
user={ "username":"Dylan", "age":"18", "password":"123" } arr=user.keys(); print(arr);
结果:dict_keys([‘username‘, ‘password‘, ‘age‘])
9.pop():移除指定key的item项
user={ "username":"Dylan", "age":"18", "password":"123" } user.pop("age"); print(user);
结果:{‘password‘: ‘123‘, ‘username‘: ‘Dylan‘}
10.popitem()-移除字典中的第一个项
user={ "username":"Dylan", "age":"18", "password":"123" } user.popitem(); print(user);
结果:{‘age‘: ‘18‘, ‘password‘: ‘123‘}
11.items():得到字典的所有值
user={ "username":"Dylan", "age":"18", "password":"123" } values=user.values(); print(values);
结果:dict_values([‘18‘, ‘Dylan‘, ‘123‘])
12.del关键字-根据指定键删除指定项
user={ "username":"Dylan", "age":"18", "password":"123" } del user["username"] print(user);
结果:{‘age‘: ‘18‘, ‘password‘: ‘123‘}
------------------------------------------------------结束-------------------------------------------------------
我就快倒下了,但是意志告诉我,坚持就是胜利,我工作直到看到明天的太阳!