目录
文章目录
python中字典的常见操作
判断字典中的元素是否存在
in 与 not in判断元素是否存在
key in dict # 返回True或False
key not in dict # 返回True或False
get()函数判断元素是否存在
bool(dict.get(key)) # 返回True或False
注意:如果key对应的value是False,0,''
,None等,那么就会返回false,这样的不准确了
例子:
字典中的popitem()函数
删除字典末尾一组键值对,并将其返回
dict.popitem() # 无需传参,返回被删除的键值对,用元组包裹,0索引是key,1索引是value
注意:如果字典为空,会报错
例子:
students = {
'小明': '到',
'小白': '在',
'小黑': '在呢'
}
print(students.popitem())
print(students)
print(students.popitem()))
print(students)
所有数据类型与其布尔值
- 每一种数据类型,自身的值都有表示Tru与False
- not对于一切结果取反
数据类型 | 为True | 为FALSE |
---|---|---|
int | 非0 | 0 |
float | 非0.0 | 0.0 |
str | len(str) != 0 | len(str) == 0 即’’ |
list | len(list) != 0 | len(list) == 0 即[] |
tuple | len(tuple) != 0 | len(tuple) == 0 即() |
dict | len(dict) != 0 | len(dict) == 0 即{} |
None | not None | None |
例子:
a_1 = 1
a_2 = 0
print(bool(a_1))
print(bool(a_2))
print(bool(not a_1))
print(bool(not a_2))
深拷贝与浅拷贝总结
类型 | 列表、字典 | 数字、字符串 |
---|---|---|
浅拷贝copy() | 拷贝父对象,不会拷贝对象内部的子对象 | 等同于赋值操作 |
深拷贝deepcopy() | 完全拷贝父对象及其子对象 | 等同于赋值操作 |
例子:
浅拷贝:
import copy
dict_1 = {
"course": "python",
"name": {"web": ["django"]}
}
dict_2 = copy.copy(dict_1)
# 修改父对象
dict_2["db"] = "mysql"
# 打印父对象内存地址
print("dict_1:", dict_1, id(dict_1))
print("dict_2:", dict_2, id(dict_2))
# 修改子对象
dict_2["name"]["web"].append("flask")
# 打印子对象内存地址
print("dict_1['name']:", dict_1, id(dict_1["name"]))
print("dict_2['name']:", dict_2, id(dict_2["name"]))
运行结果:
将浅拷贝换成深拷贝后,运行结果: