1.创建字典和给字典赋值,可以使用工厂方法dict()来创建字典,也可以使用fromkeys()来创建一个元素具有相同值的字典
>>> dict = {‘name‘:‘XiaoMing‘,‘age‘:20} >>> dict {‘age‘: 20, ‘name‘: ‘XiaoMing‘} >>> dict2 = dict(([‘x‘,1],[‘y‘,2])) >>> dict2 {‘y‘: 2, ‘x‘: 1} >>> dict2 = {}.fromkeys((‘x‘,‘y‘),1) >>> dict2 {‘y‘: 1, ‘x‘: 1
2.访问字典中的值
>>> dict = {‘name‘:‘XiaoMing‘,‘age‘:20} >>> dict {‘age‘: 20, ‘name‘: ‘XiaoMing‘} >>> for key in dict.keys(): ... print ‘key=%s,value=%s‘ % (key,dict[key]) ... key=age,value=20 key=name,value=XiaoMing
>>> for key in dict: ... print ‘key=%s,value=%s‘ % (key,dict[key]) ... key=age,value=20 key=name,value=XiaoMing
>>> dict[‘name‘] ‘XiaoMing‘
>>> ‘name‘ in dict True
3.更新字典
>>> dict[‘name‘] = ‘123‘ >>> dict[‘name‘] ‘123‘
>>> del dict[‘name‘] >>> dict {‘age‘: 20}
>>> dict {‘age‘: 20} >>> dict.pop(‘age‘) 20
时间: 2024-10-01 07:49:58