参考:b站:覃秉丰,书籍:清华大学出版社《python从入门到精通》
编译环境 python3 jupyter notebook (vscode等编译器对代码进行适当修改即可)
字典的创建
dictionary = dict() #创建空字典
dictionary = {}
dictionary = dict(zip(key,value)) #通过zip映射创建字典 key:键 value:值
dictionary = dict(key1=value1,key2=value2,...,keyn=valuen)#键-值对创建字典
dictionary = dict.fromkeys(list1) #值为空的字典 list1存放的是键
#也可以自己写字典:
dictionary ={1:'d',2:'i',5:'c',7:'t'}
访问修改字典
dictionary ={1:'d',2:'i',5:'c',7:'t'}
print(dictionary[7]) #键7的值
dictionary[7] = 'bbb' #修改键7的值
print(dictionary[7])
print(dictionary.get(1)) #get方法获取键1的值
结果
t
bbb
d
遍历字典
遍历整个字典的键值
dictionary ={1:'d',2:'i',5:'c',7:'t'}
for key,value in dictionary.items():
print('key:',key,'\t','value:',value)
结果
key: 1 value: d
key: 2 value: i
key: 5 value: c
key: 7 value: t
遍历整个字典的键
dictionary ={1:'d',2:'i',5:'c',7:'t'}
for key in dictionary.keys():
print('key:',key)
结果
key: 1
key: 2
key: 5
key: 7
遍历整个字典的值
dictionary ={1:'d',2:'i',5:'c',7:'t'}
for value in dictionary.values():
print('values:',value)
结果
values: d
values: i
values: c
values: t
排序字典的键
dictionary ={1:'d',5:'i',7:'c',2:'t'}
for key in sorted(dictionary.keys()):
print("key:",key)
结果
key: 1
key: 2
key: 5
key: 7