论坛首页 编程语言技术论坛

Python学习笔记(八):字典 dict

浏览 1302 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-11-26  
键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

字典是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
>>>
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics