var = {'a': 'A', 'b': 'B', 'c': 'C'}
字典中包含 3 个键值对
例如一本书,有书名、作者名、出版社等各种属性,可以使用字典描述如下
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
# 空字典
dict_ = {}
print(dict_,type(dict_))
dict_ = dict()
print(dict_,type(dict_))
# 输出结果
{} <class 'dict'>
{} <class 'dict'>
两种方式
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
print(book["title"])
print(book["author"])
print(book.get("press"))
print(book.get("a"))
两种方式有啥区别?
KeyError: 'authors'
两种方式
# 修改字典
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
book["author"] = "小菠萝"
print(book)
book.update({"title": "新书"})
print(book)
# 输出结果
{'title': 'Python 入门基础', 'author': '小菠萝', 'press': '机械工业出版社'}
{'title': '新书', 'author': '小菠萝', 'press': '机械工业出版社'}
# 新加键值对
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
book["money"] = 22
print(book)
# 输出结果
{'title': 'Python 入门基础', 'author': '张三', 'press': '机械工业出版社', 'money': 22}
两种方式
# 删除键值对
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
del book["press"]
print(book)
print(book.pop("author"))
print(book)
# 输出结果
{'title': 'Python 入门基础', 'author': '张三'}
张三
{'title': 'Python 入门基础'}
通过关键字 in 检查字典中是否包含指定键
# in
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
print("title" in book)
print("titles" in book)
print("张三" in book)
# 输出结果
True
False
False
获取字典中键值对的数量
# len
var = {'a': 'A', 'b': 'B', 'c': 'C'}
print(len(var))
# 输出结果
3
返回包含该字典中所有键的列表
# list
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
print(list(book))
# 输出结果
['title', 'author', 'press']
返回包含该字典中所有键的有序列表
# sorted
book = {
'title': 'Python 入门基础',
'author': '张三',
'press': '机械工业出版社'
}
print(sorted(book))
# 输出结果
['author', 'press', 'title']
dict 是一个类,而不是函数
从源码注释来看,dict 有四种传参方式,下面将一一举例
# 创建空字典
dict1 = dict()
print(dict1)
# 输出结果
{}
# 传递 list 来创建字典
mid = [("a", 1), ("b", 2)]
dict2 = dict(mid)
print(dict2)
# 输出结果
{'a': 1, 'b': 2}
iterable 的详解:https://cloud.tencent.com/developer/article/1814243
# 传递关键字参数来创建字典
dict3 = dict(name="yy", age=24)
print(dict3)
# 输出结果
{'name': 'yy', 'age': 24}
mid = {"title": [1, 2, 3]}
# 相当于浅拷贝
dict4 = dict(mid)
print(dict4)
print(id(mid), id(dict4))
mid["name"] = "test"
mid["title"][1] = 1
print(mid, dict4)
# 输出结果
{'title': [1, 2, 3]}
4498981760 4500413824
{'title': [1, 1, 3], 'name': 'test'} {'title': [1, 1, 3]}
这种传参方式相当于浅拷贝,新的字典对象和旧的字典对象并不指向同一个对象引用
假设直接用赋值的方式,因为字典是可变对象,所以新旧字典对象都会指向同一个对象引用
dict1 = {1: 1}
dict2 = dict1
print(id(dict1), id(dict2))
# 输出结果
4355281792 4355281792
所以,当想复制一个新的字典对象但是又不想指向同一个对象引用的话,最好还是使用 dict() 的方式
https://cloud.tencent.com/developer/article/1857020
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有