py.字典

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后

添加
悬浮,盘旋
剥夺,去除
连接
控制台

4.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值