Python3 学习笔记9_字典_20180228

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 学习网站:www.runoob.com

#****************************************************
#                   Python3 字典                  *
#****************************************************
print ("--------------------分割线------------------")
'''
字典是另一种可变容器模型,且可存储任意类型对象,字典的每个键值对
key与value之间用冒号(:)分隔,每个键值对之间用逗号(,)分隔,整个字典
包括在花括号{}中。
格式: d = { key1:value1, key2:value2 }

键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变
的,如字符串、数字或元组。
'''
dict1 = { 'Alice':'1234', 110:120 }
print( dict1 )                      # {'Alice': '1234', 110: 120}

#============
# 访问字典值
#============
dict2 = {'name':'bugliu', 'age':7}
print( dict2['name'] )              # bugliu

# 如果用字典里没有的键访问数据,会输出错误
# print( dict2['aaa'] )             # KeyError: 'aaa'

#============
# 修改字典
#============
# 更新字典值
dict2['age'] = 66
print( dict2['age'] )               # 66

# 添加新键值对
dict2['class'] = 'CET'
print( dict2['class'] )             # CET

# 删除字典键
del dict2['age']
print( dict2 )                      # {'name': 'bugliu', 'class': 'CET'}

# 清空字典
dict2.clear()
print( dict2 )                      # {}

# 删除字典
del dict2
# print( dict2 )                    # name 'dict2' is not defined
print ("--------------------分割线------------------")

#============
# 字典键特性
#============
# 字典值可以是任何的python对象,既可以是标准的对象,也可以是用户
# 自定义的,但键不行。

# 不允许同一个键出现两次。如果同一个键被赋值两次,后一个值会被记住
dict_t = { 'name':'jim', 'age':8, 'name':'tom' }
print( dict_t['name'] )             # tom

# 键必须不可变,所以可以用数字,字符串或元组充当,而用列表不行
dict_t = { ('name',):'jim', 'age':8 }   #{('name',): 'jim', 'age': 8}
print( dict_t )
print( dict_t[('name',)] )              # jim
print ("--------------------分割线------------------")

#============
# 字典函数
#============
dict_x = {'name':'bugliu', 'age':9}

# 计算字典元素个数,即键的总数
print( len(dict_x) )                # 2

# 输出字典,以可打印的字符串表示
print( str(dict_x) )                # {'name': 'bugliu', 'age': 9}

# 返回输入变量的类型
print( type(dict_x) )               # <class 'dict'>
print ("--------------------分割线------------------")

#============
# 字典内置方法
#============
dict_x = { 'len':9, 'wigth':5 }
dict_y = { 'num':100, 'sum':1050 }

# 删除字典内的所有元素
dict_x.clear()
print( len(dict_x) )                # 0

# 返回一个字典的复制
dict_m = dict_y.copy()
print( dict_m )                     # {'num': 100, 'sum': 1050}

# 返回指定键的值,如果值不在字典中返回default值
print( dict_y.get('num') )          # 100
print( dict_y.get('numm') )         # None
# 999 为键值不存在,默认返回值
print( dict_y.get('numm', 999) )    # 999

# 键在字典里返回true,否则返回false
print( 'num' in dict_y )            # true

# 以列表返回一个字典所有的键
print( dict_y.keys() )              # dict_keys(['num', 'sum'])

# 以列表返回一个字典所有的值
print( dict_y.values() )            # dict_values([100, 1050])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值