1、dict.keys() 获取字典所有的键。python3的keys()方法,返回的是迭代器。可以用list返回列表形式。
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.keys()
b=list(b)
print(b) 结果:['name', 'age', 'gender', 'hobby']
2、dict.values() 获取字典所有的值。python3的values()方法,返回的是迭代器。可以用list返回列表形式。
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.values()
b=list(b)
print(b) 结果:['zhangsan', 12, 'man', 'play game']
3、dict.items() 返回可遍历的(键,值)元组数组。(返回了一个列表,列表中包含数个元组,每个元组中的内容对应的就是字典中的键值对)
通常是要通过for循环取出,键和值
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
For key,value in a.items():
print(key,value)
结果:
Name zhangsan
age 12
gender man
hobby play game
4、dict.get() 通过指定的键,获取对应的值
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.get("name")
print(b) 结果:zhangsan
5、dict.pop() 删除指定的键,返回值就是删除的键对应的值
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.pop("name")
print(b) 结果:zhangsan
print(a) 结果:{'age': 12, 'gender': 'man', 'hobby': 'play game'}
6、dict.popitem() 删除最后一个键,返回的是删除的键值对(元组类型)
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.popitem()
print(b) 结果:('hobby', 'play game')
print(a) 结果:{'name': 'zhangsan', 'age': 12, 'gender': 'man'}
7、dict.clear() 删除字典内的所有元素,该方法没有返回值
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.clear()
print(len(a)) 结果:0
8、dict.setdefault() 如果指定的键存在,那么直接返回键对应的值;
如果指定的键不存在,那么就会添加键,并且第二个参数作为键的值
a={"name":"zhangsan","age":12,"gender":"man","hobby":"playgame"}
b=a.setdefault("name","hhhh")
print(b) 结果:zhangsan
print(a) 结果:{'name': 'zhangsan', 'age': 12, 'gender': 'man', 'hobby': 'play game'}
c=a.setdefault("job","student")
print(c) 结果:student
print(a) 结果:{'name': 'zhangsan', 'age': 12, 'gender': 'man', 'hobby': 'play game', 'job': 'student'}
9、dict.fromkeys() 用于创建一个新的字典,并以可迭代对象中的元素分别作为字典中的键,且所有键对应同一个值,默认位None。
返回值:返回一个新字典。
iterable1 = "12" # 字符串
iterable2 = [1,2] # 列表
iterable3 = (1,2) # 元祖
iterable4 = {1:'one',2:'two'} # 字典
v1 = dict.fromkeys(iterable1,'字符串')
v2 = dict.fromkeys(iterable2,'列表')
v3 = dict.fromkeys(iterable3,'元祖')
v4 = dict.fromkeys(iterable4,'字典')
v5 = dict.fromkeys(iterable4) #value默认为None
print(v1) 结果:{'1': '字符串', '2': '字符串'}
print(v2) 结果:{1: '列表', 2: '列表'}
print(v3) 结果:{1: '元祖', 2: '元祖'}
print(v4) 结果:{1: '字典', 2: '字典'}
print(v5) 结果:{1: None, 2: None}
10、dict.copy() 复制字典
a={'Name':'Runoob','Age':7,'Class':'First'}
b=a.copy()
print(b) 结果:{'Name': 'Runoob', 'Age': 7, 'Class': 'First'}