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)
时间: 2024-10-25 08:22:46