2021.4.13
1.字典概念
{键:值,键:值}------用花括号括起来,键是字符创,而与键对应的值可以是任何python中的对象,键值对间用逗号分隔
2.字典的增删改查
(1)、增和改都是通过赋值的形式来实现
(2)、查就类似列表访问
(3)、删则使用del 语句
favorite_city = {
'Simon': '重庆',
'Jack': '杭州',
'James': '克利夫兰',
'David': '台北'
}
#查
print("查")
print("Simon's favorite city is " + favorite_city['Simon'])
#增
print("增")
favorite_city['陈顺'] = '郴州'
print(favorite_city)
#改
print("改")
favorite_city['Simon'] = '郴州'
print(favorite_city)
#删
print("删")
del favorite_city['James']
print(favorite_city)
输出
查
Simon's favorite city is 重庆
增
{'Simon': '重庆', 'Jack': '杭州', 'James': '克利夫兰', 'David': '台北', '陈顺': '郴州'}
改
{'Simon': '郴州', 'Jack': '杭州', 'James': '克利夫兰', 'David': '台北', '陈顺': '郴州'}
删
{'Simon': '郴州', 'Jack': '杭州', 'David': '台北', '陈顺': '郴州'}
3.遍历字典
(1)、键-值对遍历
for 变量1, 变量2 in 字典.items():
print( 变量1)
print(变量2)
ps:items()方法返回的是一个键-值对列表
program_word = {
'strip': '剥夺,去除',
'append': '添加',
'concatenate': '连接',
'hover': '悬浮,盘旋',
'console': '控制台'
}
for word, translation in program_word.items():
print(word + ':' + translation)
输出
strip:剥夺,去除
append:添加
concatenate:连接
hover:悬浮,盘旋
console:控制台
(2).遍历键值
for 变量名 in 字典.keys():
print(变量名)
ps:keys()返回的是包含所有键值的列表,相当于一个字符串列表,故可对该列表使用sorted()函数和sort()方法,sorted(字典.keys())
program_word = {
'strip': '剥夺,去除',
'append': '添加',
'concatenate': '连接',
'hover': '悬浮,盘旋',
'console': '控制台'
}
for word in program_word.keys():
print(word)
print("排序后:")
for word in sorted(program_word.keys()):
print(word)
输出
strip
append
concatenate
hover
console
排序后:
append
concatenate
console
hover
strip
(3).遍历值
for 值 in 字典.values():
print(值)
ps:values()方法返回的是包含所有值的列表,该列表中可能包含重复的值,可通过set()函数来把列表变成集合,从而保证元素互不相同
program_word = {
'strip': '剥夺,去除',
'append': '添加',
'concatenate': '连接',
'hover': '悬浮,盘旋',
'console': '控制台',
'add': '添加'
}
for translation in program_word.values():
print(translation)
print("\n使用set后\n")
for translation in set(program_word.values()):
print(translation)
输出
剥夺,去除
添加
连接
悬浮,盘旋
控制台
添加
使用set后
添加
悬浮,盘旋
剥夺,去除
连接
控制台