dict的几个要点
1. 采用key,value键-值对进行存储
2. key必须是不可变对象
3. key值不能重复
添加元素:
aDict = {'1':'aaa','b':'bbb','3':'ccc'}
aDict['d'] = 'ddd'
print aDict
==> {'1': 'aaa', '3': 'ccc', 'b': 'bbb', 'd': 'ddd'}
删除元素:
aDict = {'1':'aaa','b':'bbb','3':'ccc'}
del(aDict['1'])
==> {'3': 'ccc', 'b': 'bbb'}
aDict = {'1':'aaa','b':'bbb','3':'ccc'}
aDict.pop('b')
==> {'1':'aaa','3': 'ccc'}
清空dict:
aDict.clear()
遍历dict:
aDict = {'1':'aaa','b':'bbb','3':'ccc'}
通过键-值方式遍历:
for k in aDict:
print "%s:%s" %(k,aDict[k])
通过items方式遍历:
for k,v in aDict.items():
print "%s:%s" %(k,v)
通过iteritems方式遍历:
for k,v in aDict.iteritems():
print "%s:%s" %(k,v)
通过iterkeys和itervalues方式遍历:
for k,v in zip(aDict.iterkeys,aDict.itervalues):
print "%s:%s" %(k,v)
posted on 2017-03-13 22:45 CodeForJoy 阅读(171) 评论(0) 编辑 收藏 举报