菜鸟第一篇 字典函数 1

作为初学python的菜鸟一枚,今天复习的是字典函数。

1、字典函数是用{ }表示的。字典里'k' 与'v'即键与值是一 一对应的。
2、字典函数 keys 、 values、 items分别对应字典的键、值和键-值对。

例 :>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
        >>> spam.keys()
dict_keys(['color', 'name', 'age'])
         >>> spam.values()
dict_values(['red', 'Mary', '25'])
          >>> spam.items()
dict_items([('color', 'red'), ('name', 'Mary'), ('age', '25')])
 3、还可以通过字典的某一键访问这个键对应的值。若访问的键不存在,则会有KeyError出错信息。

>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
>>> spam['name']
'Mary'
这里访问键对应的值要用方括号。
4、字典不能像列表那样切片,因为字典是不排序的。
5  in 或not in 检查某个键或值是否存在于字典中。
例:>>> spam = {'name': 'Mary', 'color': 'red', 'age': '25'}
       >>> 'name' in spam.keys()   # 'name' in spam 是简写版本
         True6
6、get( )函数:在访问一个键的值之前,检查该键是否存在于字典中。get(a, b)有2个参数,第一个参数是访问字典中的这个键,第2个参数是该键不存在的时候返回的备用值。
例:>>> picnicItems = {'apples': 5, 'cups': 2}

      >>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups'
       'I am bringing 2 cups'
       >>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' cups'
      'I am bringing 0 cups'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值