# 定义一个字典dict={'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}print(dict)# {'start': 'There is a new start', 'second': 'This a dictionary', 'third': "Let's go"}# 访问字典中的值print(dict['second'])# This a dictionary# 向字典中一次加入键值对dict['four']='This is add for dictionary'print(dict)'''
{'start': 'There is a new start',
'second': 'This a dictionary',
'third': "Let's go",
'four': 'This is add for dictionary'}
'''# 错误示例,不是所有的值可以作Keydict[['four']]='This is add for dictionary'# 会报错 TypeError: unhashable type: 'four'# 向字典中批量加入键值对dict.update({'five':'This a fifth dictionary key-value','six':'This a sixth dictionary key-value'})print(dict)'''
{'start': 'There is a new start',
'second': 'This a dictionary',
'third': "Let's go",
'five': 'This a fifth dictionary key-value',
'six': 'This a sixth dictionary key-value'}
'''# 删除字典中的某一个键值对,不获取删除的键对应的值deldict['third']print(dict)# {'start': 'There is a new start', 'second': 'This a dictionary'}# 删除字典中的某一个键值对,获取删除的键对应的值print(dict.pop('third'))# Let's go
# 使用get()方法返回给定键的值# 如果要获取的键存在,则返回字典中对应的值;否则返回给定的默认值dict={'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}print(dict.get('start',0))# There is a new start# 如果要获取不存在的键,其值未设置默认值,则默认返回Noneprint(dict.get('ten'))# None# 如果要获取不存在的键,其值设已经设置默认值,则返回默认值print(dict.get('ten',0))# 0
# 遍历返回字典中的所有键dict={'start':'There is a new start','second':'This a dictionary','third':'Let\'s go'}print(dict.keys())# dict_keys(['start', 'second', 'third'])# 遍历返回字典中的所有值print(dict.values())# dict_values(['There is a new start', 'This a dictionary', "Let's go"])# 通过key遍历输出keyfor key indict:print(key)'''
start
second
third
'''# 通过键值对,遍历输出键值对for key,value indict.items():print(key,value)'''
start There is a new start
second This a dictionary
third Let's go
'''
tup =('first','second','first',2,5)for item in tup:print(item)'''
first
second
first
2
5
'''
06、元组拆包
x,y =(2,3)print("Value of x is {}, the value of y is {}.".format(x,y))# Value of x is 2, the value of y is 3.
07、枚举
枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
tups =('first','second','first',2,5)print(enumerate(tups))# <enumerate object at 0x000002737049B680># 遍历输出for index,tup inenumerate(tups):print(index,tup)'''
0 first
1 second
2 first
3 2
4 5
'''
三、元组相对列表的优势
01、访问元组比列表快
如果要定义一组常量,要做的工作是迭代它。元组比列表更适合定义常量
使用timeit库部分测量性能差异 ,为Python代码计时(以秒为单位)
import timeit
print('Tuple time:',timeit.timeit('x = (1,2,3,4,5,6)', number =1000000))print('List time:',timeit.timeit('x = [1,2,3,4,5,6]', number =1000000))'''
Tuple time: 0.049612699999999996
List time: 0.10503829999999999
'''