字典的用法

 1 __author__ = 'ZZG'
 2 
 3 #key-value
 4 #字典无序,没有下标,通过key来寻找
 5 info ={
 6     'cat':'animal',
 7     'flower':'plant',
 8     'lemon':'fruit'}
 9 
10 print(info)
11 
12 #查找
13 print(info['cat'])
14 print(info.get('cat'))
15 print('cat'in info)
16 
17 #更改字典中的值
18 info['lemo']='水果'
19 print(info)
20 
21 #创建一个键值对
22 info['book']='none'
23 print(info)
24 
25 #删除字典
26 del info['book']
27 info.pop('cat')
28 info.popitem()#随意删除一个
29 print(info)

 #设置默认字典用法

1 info ={
2     'cat':'animal',
3     'flower':'plant',
4     'lemon':'fruit'}
5 
6 info.setdefault("dog",'animal')
7 print(info)
View Code

#update的用法

 1 a = {
 2     'student1':"xiaoming",
 3     'student2':'xiaozhang',
 4     'student3':'xiaoxi'}
 5 b = {
 6     'student1':'zhangshuai',
 7     'student4':'liuhua',
 8     'student5':'jincai',
 9     1:2,
10     2:3}
11 a.update(b)
12 print(a)
View Code

 #items 用法将字典转换为列表

1 a = {
2     'student1':"xiaoming",
3     'student2':'xiaozhang',
4     'student3':'xiaoxi'}
5 
6 print(a.items())
View Code

#初始化一个新的字典

1 c = dict.fromkeys([1,2,3], "姓名")
2 print(c)
View Code

#字典的循环

 1 a = {
 2     'student1':"xiaoming",
 3     'student2':'xiaozhang',
 4     'student3':'xiaoxi'}
 5 #推荐的循环
 6 for i in a:
 7     print(i,a[i])
 8 #另一种循环
 9 for v,k in a.items():
10     print(v,k)
View Code

 

转载于:https://www.cnblogs.com/zzg-home/p/7058981.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值