浏览 1302 次
锁定老帖子 主题:Python学习笔记(八):字典 dict
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-11-26
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。 字典是dict类的实例/对象。 #!/usr/bin/python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook 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'; # Deleting a key/value pair del ab['Spammer']; print('\nThere are %d contacts in the address-book\n' % len(ab)); for name, address in list(ab.items()): print('Contact %s at %s' % (name, address)); if 'Guido' in ab: # OR ab.has_key('Guido') print("\nGuido's address is %s" % ab['Guido']); 结果: >>> Swaroop's address is swaroopch@byteofpython.info There are 4 contacts in the address-book Contact Swaroop at swaroopch@byteofpython.info Contact Guido at guido@python.org Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wall.org Guido's address is guido@python.org >>> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |