dict的常见问题

简介: 1、使用key和value的这种方法样例:

一、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


相关文章
|
12月前
|
缓存 NoSQL 数据建模
【Redis源码】dict字典学习(三)
【Redis源码】dict字典学习(三)
74 0
|
4月前
|
机器学习/深度学习 监控 物联网
函数计算操作报错合集之调用接口提示Cannot copy out of meta tensor; no data! 是什么原因
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
125 0
|
2月前
dict 和 set 的 8 个经典使用例子
dict 和 set 的 8 个经典使用例子
30 4
|
4月前
|
存储 Python
Python中list, tuple, dict,set的区别和使用场景
Python中list, tuple, dict,set的区别和使用场景
|
5月前
|
存储 安全 Java
Python教程第3章 | 集合(List列表、Tuple元组、Dict字典、Set)
Python 列表、无序列表、字典、元组增删改查基本用法和注意事项
90 1
|
5月前
|
网络协议 API 开发者
Python 3.9 性能优化:更快的 list()、dict() 和 range() 等内置类型
Python 3.9 性能优化:更快的 list()、dict() 和 range() 等内置类型
42 1
dict中所有方法的使用
提示:以下是本篇文章正文内容,下面案例可供参考
51 0
|
存储 Python
Python基础 | 比系统自带dict()更方便的字典EasyDict
Python基础 | 比系统自带dict()更方便的字典EasyDict
103 0
|
Python
python中进一步理解字典,items方法、keys方法、values方法
python中进一步理解字典,items方法、keys方法、values方法
150 0