Python字典

字典

字典是键值对的无序可变序列。
字典中的键可以是任何不可变数据,如整数、实数、复数、字符串和元组等,不可用列表、集合和字典等可变类型。

字典的创建

>>> m = {'a':1, 'b':2, 'c':3}
>>> print(type(m),m)
<class 'dict'> {'b': 2, 'a': 1, 'c': 3}

>>> keys = ['a','b','c']
>>> values = [3,2,1]
>>> dictionary = dict(zip(keys,values))
>>> print(type(dictionary),dictionary)
<class 'dict'> {'b': 2, 'a': 3, 'c': 1}


>>> ##使用内置函数dict()创建字典
>>> d = dict(ID = '1001',name = '小王')
>>> print(type(d),d)
<class 'dict'> {'ID': '1001', 'name': '小王'}

>>> d = dict(ID = ('1001','1002'),name = ('小王','小李'))
>>> print(type(d),d)
<class 'dict'> {'ID': ('1001', '1002'), 'name': ('小王', '小李')}


>>> ##创建值为空的字典
>>> aDict = dict.fromkeys(['name','age','gender'])
>>> aDict
{'age': None, 'name': None, 'gender': None}

字典元素的读取

  1. 通过字典的键访问字典,若键不存在则抛出异常
    >>> aDict = {'name':'小王', 'gender':'male', 'age':20}
    >>> aDict['name']
    '小王'
  1. 通过更加安全的方法get()方法访问字典对象元素,键不存在时默认返回None,也可以返回指定的值
>>> aDict.get('name')
'小王'
>>> aDict.get('ID')
>>> temp = aDict.get("ID")
>>> temp is None
True
>>> temp == None
True


>>> aDict['subjects'] = aDict.get('score',[])
>>> aDict['subjects'].append('数值分析')
>>> aDict['subjects'].append('英语写作')
>>> aDict
{'subjects': ['数值分析', '英语写作'], 'age': 20, 'name': '小王', 'gender': 'male'}

items()返回键值对列表
keys()返回键列表
values()返回值列表

>>> aDict
{'subjects': ['数值分析', '英语写作'], 'age': 20, 'name': '小王', 'gender': 'male'}
>>> aDict.items()
dict_items([('subjects', ['数值分析', '英语写作']), ('age', 20), ('name', '小王'), ('gender', 'male')])
>>> aDict.keys()
dict_keys(['subjects', 'age', 'name', 'gender'])
>>> aDict.values()
dict_values([['数值分析', '英语写作'], 20, '小王', 'male'])

对字典元素的操作

添加键值对或者修改键对应的值

>>> aDict['gender'] = 'female'
>>> aDict['home'] = 'China'
>>> aDict
{'subjects': ['数值分析', '英语写作'], 'age': 20, 'home': 'China', 'name': '小王', 'gender': 'female'}

update()方法一次性添加多个键值对

>>> bDict = {'c':3}
>>> bDict.update({'a':1,'b':2})
>>> bDict
{'b': 2, 'a': 1, 'c': 3}

字典的删除

>>> cDict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#del命令删除字典指定键对应的元素
>>> del(cDict['a'])
>>> cDict
{'d': 4, 'f': 6, 'b': 2, 'e': 5, 'c': 3}

>#字典函数pop()删除并返回指定键的元素
>>> cDict.pop('d')
4

#没有参数,删除并返回字典中的一个元素
>>> cDict.popitem()
('f', 6)

#清空字典中所有元素
>>> cDict.clear()
>>> cDict
{}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值