版权申明:原创文章,未经博主同意,不得转载!
Python从入门到上瘾10——字典
小白高效学习Python系列,50小时学会Python “ 阅读本文需要大约8分钟。”
在Python中,除列表,元组外,还要一类重要的数据结构–字典。字典与列表的最大区别在于,字典是无序的,不能通过位置索引来访问成员。那怎么访问字典的成员呢?带着问题阅读下文。
字典的基本用法
字典是一种可变容器,可存储任意类型成员对象,并用花括号“{}”进行标识中。字典的每个键值”key:value“对用冒号(:)分割,每个键值对之间用逗号“,”分割,示例代码如下:
dict = {'MotherBoard': '关注', 'Python': '学习'} # 包括两个键值对。
dict1 ={} #创建空字典
对键值对的访问,即把相应的键放入到方括号中,如下所示
dict = {'MotherBoard': '关注', 'Python': '学习'}
print(dict['MotherBoard']) #输出结果为 ‘关注’
修改字典元素,即修改原有的键/值对
dict = {'Name': 'MotherBoard', 'Age': 1}
dict['Age'] = 8 # 修改 Age
print (dict['Age']) #输出结果为 8
向字典中元素,即增加新的键/值对
dict = {'Name': 'MotherBoard'}
dict['School'] = "MotherBoard" # 添加信息
print (dict) # 输出字典,输出结果为 {'Name': 'MotherBoard', 'School': 'MotherBoard'}
删除字典元素,利用del进行删除
dict = {'Name': 'MotherBoard', 'Age': 1}
del dict['Age'] # 删除 Age
print (dict) #输出字典,输出结果为 {'Name': 'MotherBoard'}
注意:
- 字典的值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的;字典的键必须不可变,可以用数字、字符串或元组充当,但不能是列表,如下例所示
dict = {['Name']: 'MotherBoard', 'Python': '学习'} # 字典的键不能是列表
print("dict['Name']: ", dict[['Name']])
#输出结果:Traceback (most recent call last):
# File "test.py", line 3, in <module>
# dict = {['Name']: 'MotherBoard', 'Python': '学习'}
#TypeError: unhashable type: 'list'
但字典的键可以是元组
dict = {('Name'): 'MotherBoard', 'Python': '学习'} # 键可以用元组
print("dict['Name']: ", dict[('Name')])
- 字典创建时如果同一个键被赋值两次,前一个值会被后一个值覆盖,如下:
dict = {'Name': 'god', 'Name': 'MotherBoard'}
print ( dict['Name']) #输出结果:MotherBoard
字典遍历
在实际程序中,常常需要对存放在字典中的数据进行遍历。Python中可以利用for循环对字典的键值对,或者单独对键、值进行遍历。
- 对键值对的遍历
dict = {'MotherBoard': '关注', 'Python': '学习'}
for key, value in dict.items():
print('key:'+ key)
print('value'+value)
#输出结果如下:
#key:MotherBoard
#value关注
#key:Python
#value学习
for循环中申明了两个变量“key, value”,实际上这两个变量的名称可以任取,“key, value”存储了dict.items()返回的键值对。
- 对键的遍历
dict = {'MotherBoard': '关注', 'Python': '学习'}
for key in dict.keys():
print('key:'+ key)
#输出结果如下:
#key:MotherBoard
#key:Python
for循环中申明了变量“key”,该变量存储了dict.keys()返回的键。
注意,上述代码与下面代码等价:
dict = {'MotherBoard': '关注', 'Python': '学习'}
for key in dict: #省略keys()
print('key:'+ key)
#输出结果如下:
#key:MotherBoard
#key:Python
- 对值的遍历
dict = {'MotherBoard': '关注', 'Python': '学习'}
for value in dict.values():
print('value:'+value)
#输出结果如下:
#value:关注
#value:学习
也可以将返回的值存储在列表中:
dict = {'MotherBoard': '关注', 'Python': '学习'}
print(list(dict.values()))
#输出结果如下:
#['关注', '学习']
字典的内置方法
- clear()方法清空字典
dict = {'MotherBoard': '关注', 'Python': '学习'}
print(len(dict)) #输出结果为2
dict.clear() #删除字典
print(len(dict)) #输出结果为0
- get(key)方法获取指定的键值
dict = {'MotherBoard': '关注', 'Python': '学习'}
print(dict.get('Python')) #输出结果为‘学习’
- copy()方法复制字典
dict = {'MotherBoard': '关注', 'Python': '学习'}
dict2 = dict.copy()
print(dict2) #输出结果为{'MotherBoard': '关注', 'Python': '学习'}
- setdefault(key, default=None)获取指定的键值,若键值不存在,添加该键值对,并将该键值对的值设定为指定值。
dict = {'MotherBoard': '关注', 'Python': '学习'}
dict.setdefault('Python', '默认值') #键值对存在,默认值不起作用
print(dict) #输出结果为{'MotherBoard': '关注', 'Python': '学习'}
dict.setdefault('深度学习', '默认值') #键值对不存在,添加该键值对
print(dict) #输出结果为{'MotherBoard': '关注', 'Python': '学习', '深度学习': '默认值'}
- fromkeys(seq [, value])创建新字典,其中seq为用来创建字典键的列表或者元组,value为可选的默认值。没看懂这句话说的啥,那么看下面代码:
seq=('motherboard','python') #用来创建字典的键值的元组,也可用列表
dict1 = dict.fromkeys(seq) #未设定默认值,系统默认为None
print(dict1) #显示结果:{'motherboard': None, 'python': None}
dict2 = dict.fromkeys(seq,666) #默认值设定为666
print(dict2) #显示结果:{'motherboard': 666, 'python': 666}
- update()修改字典,语法如下dict.update(dict2),即把字典dict2的“键值”对更新到字典dict中。
dict = {'MotherBoard': '关注', 'Python': '学习'}
dict2 = {'人工智能':'21世纪'}
dict.update(dict2)
print(dict) #显示结果:{'MotherBoard': '关注', 'Python': '学习', '人工智能': '21世纪'}
- 本期到此结束,关注本人公众号,一起学习进步!