字典的所有方法解释:
d.clear():清空字典
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple2.clear()
print(tuple2)
--》{}
d.copy():复制;将字典元素复制给另外一个字典,字典的值发生变化,不会影响另外一个字典
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple4 = tuple2.copy()
print(tuple4)
tuple4[1] = 'f'
print(tuple4)
--》{1: 'f', 2: 'b', 3: 'c', 4: 'd'}
print(tuple2)
--》{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
d.get(key,返回值):查找指定key的值,找到返回key的value,找不到返回指定的返回值
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.get(5,-1)
print(tuple3)
--》:-1
d.items():返回字典中的所有的键值对,返回的是列表格式
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.items()
print(tuple3)
--》dict_items([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')])
d.keys():返回字典的所有的key值,返回的是列表格式
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.keys()
print(tuple3)
--》dict_keys([1, 2, 3, 4])
d.values():返回字典中所有的value值,返回的是列表格式
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.values()
print(tuple3)
-->dict_values(['a', 'b', 'c', 'd'])
d.pop(key[,返回值]):删除字典中指定key,并返回key的值,没有找到指定的key,返回返回值,不指定返回值,报错
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.pop(5,-1)
print(tuple3)
--》-1
popitem():删除字典中末尾的key-value对,并返回key-value
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.popitem()
print(tuple3)
--》(4,'d')
d.setdefault(key,default):查找key是否在字典中存在,存在则返回存在key对应的value
如果不存在,将把key添加到字典中
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = tuple2.setdefault(4,'f')
print(tuple3)
-->d
print(tuple2)
-->{1:"a",2:"b",3:"c",4:"d"}
#注意字典中不能使用+连接
update():将一个字典更新到另一个字典中去,如果两个字典中key一样,将更新的值替换还原的值
举例:
tuple2 = {1:"a",2:"b",3:"c",4:"d"}
tuple3 = {5:'f',6:"g",1:'t'}
tuple2.update(tuple3)
print(tuple2)
--》{1: 't', 2: 'b', 3: 'c', 4: 'd', 5: 'f', 6: 'g'}