9.1 字典的基本概念
基本形式:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
字典用于在键值对中存储数据值。字典是有序*、可变且不允许重复的集合。(从 Python 3.7 版开始,字典是有序的。在 Python 3.6 及更早版本中,字典是无序的。)
9.1.1 创建字典与访问
字典是用大括号写的,有键和值。
创建并打印字典:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
字典项是有序的、可变的,并且不允许重复。字典项以键值对的形式呈现,可以使用键名进行引用。
例如打印brand的值
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
9.1.2 字典长度
还是用用len函数
hisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
9.1.3 数据类型
(1)字典项中的值可以是任何数据类型:
例如:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
类型:dict()
(2)打印字典的数据类型:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type(thisdict))
(3)与其他数据类型的区别
列表是有序且可变的,允许重复元素;
元组是有序且不可更改的,允许重复元素;
集合是无序且无索引的,无重复元素;
字典是有序且可变的,无重复元素。
9.2 字典的“增”
9.2.1 关键词索引添加
比如我要添加一个年龄为20:
thisdict = {
"name": "hg",
"address": "长沙",
"year": 2000
}
thisdict['age']=21
print(thisdict)
9.2.2 使用update
thisdict = {
"name": "hg",
"address": "长沙",
"year": 2000
}
thisdict['age']=21