一、dict中扩展字典长度(多种方法)
1、使用key和value的这种方法
样例:
dict_var = {1: 2, 2: 4} print(dict_var) dict_var[5] = 5 print(dict_var)
# 输出 {1: 2, 2: 4} {1: 2, 2: 4, 5: 5}
2、使用setdefault方法
样例:
dict_var = {1: 2, 2: 4} print(dict_var) dict_var.setdefault(4, 4) print(dict_var)
# 输出 {1: 2, 2: 4} {1: 2, 2: 4, 4: 4}
3、使用update方法
样例:
dict_var = {1: 2, 2: 4} print(dict_var) dict_var.update({6: 5}) print(dict_var)
# 输出 {1: 2, 2: 4} {1: 2, 2: 4, 6: 5}
二、dict中获取所有的key,获取所有的value,获取所有的item
1、获取所有的key(使用keys方法)
样例:
dict_var = {1: 2, 3: 4, 4: 5, 8: 0} return_value = dict_var.keys() print(return_value, type(return_value))
# 输出 dict_keys([1, 3, 4, 8]) <class 'dict_keys'>
2、获取所有的value(使用values方法)
样例:
dict_var = {1: 2, 3: 4} return_value = dict_var.values() print(return_value, type(return_value))
# 输出 dict_values([2, 4]) <class 'dict_values'>
3、获取所有的item(使用items方法)
样例:
dict_var = {1: 2, 3: 4} return_value = dict_var.items() print(return_value, type(return_value))
# 输出 dict_items([(1, 2), (3, 4)]) <class 'dict_items'>
三、dict中通过一个不存在的key去获取值(要求不报错)
1、使用get方法
dict_var = {1: 2, 2: 4} return_value = dict_var.get(3) print(return_value)
# 输出 None
2、使用pop方法,如果未找到 key,我们可以给定一个值
样例:
dict_var = {1: 2, 2: 4} return_value = dict_var.pop(3, 4) print(return_value)
这个字典不存在key=3的值,我们使用pop方法,自定义一个值为4
# 输出 4