- 👨💻作者简介: 大家好,我是小火车~~
- 🛳️个人主页: 上进小火车的博客
- 📗系列专栏: 本文收藏在《Python基础从0到1》专栏
- ✉️如果文章知识点有错误的地方,请指正! 和大家一起学习一起进步🎈
- 🔥如果觉得博主的文章还不错的话,请👍三连支持👍一下博主哦
- ➡️各系列思维导图链接
Python字典和集合
一🥖. 字典
1.1 字典定义
字典(dictionary)是包含若干“键:值”元素的无序可变序列,字典中的每个元素包含“键”和“值”两部分,定义字典时,每个元素的键和值用冒号分隔,元素之间用逗号分隔,所有的元素放在一对大括号“{}”中。字典中的键可以为任意不可变数据,比如整数、实数、字符串、元组等等。
1.2 字典的创建
- 使用“=”将一个字典赋值给一个变量
>>> a_dict = {
'server': 'db.neuedu.com', 'database': 'mysql'}
>>> a_dict
{
'database': 'mysql', 'server': 'db.neuedu.com'}
>>> x = {
} #空字典
>>> x
{
}
- 使用dict()利用已有数据创建字典
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{
'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{
}
- 使用dict()根据给定的键、值创建字典
>>> d = dict(name='Dong', age=37)
>>> d
{
'age': 37, 'name': 'Dong'}
- 以给定内容为键,创建值为空的字典
>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{
'age': None, 'name': None, 'sex': None}
1.3 字典元素的读取
- 以键作为下标可以读取字典元素,若键不存在则抛出异常
>>> aDict = {
'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
'Dong'
>>> aDict['tel'] #键不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
aDict['tel']
KeyError: 'tel'
- 使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值。
>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))
SDIBT
>>> aDict['score'] = aDict.get('score',[])
>>> aDict['score'].append(98)
>>> aDict['score'].append(97)
>>> aDict
{
'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
- 使用字典对象的items()方法可以返回字典的键、值对列表
>>> aDict={
'name':'Dong', 'sex':'male', 'age':37}
>>> for item in aDict.items(): #输出字典中所有元素<