'''
Created on 2011-11-1
@author: dudong0726
python中所谓的字典其实就是java中的map,操作类似
'''
if __name__ == '__main__':
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print("Swaroop's address is %s" % ab['Swaroop'])
# Adding a key/value pair
ab['Guido'] = 'guido@python.org' #通过key引用,如果key不存在,为添加新项
# Deleting a key/value pair
del ab['Spammer'] #通过key删除项
# Modify a key/Value pair
ab['Larry'] = 'Larry broth@well.org'; #修改某一项内容
print ('\nThere are %d contacts in the address-book\n' % len(ab))
for name,address in ab.items():
print('Contact %s at %s' % (name,address)) #遍历ab,返回类似于集合的对象,
if 'Guido' in ab: # OR ab.has_key('Guido')
print ("\nGuido's address is %s" % ab['Guido'])
发现一个比较有趣现象,替换上面红色代码,得到同样的结果,
for item in ab.items():
print('Contact %s at %s' % item) #遍历ab,返回类似于集合的对象,