键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
字典是dict类的实例/对象。
例:
#!/usr/bin/env python
#coding:utf8
contacts = { 'Admin' : 'admin@jb51.net',
'Linuxeye' : 'linuxeye@jb51.net',
'Support' : 'support@jb51.net'
}
print "Linuxeye's address is %s" % contacts['Linuxeye']
# Adding a key/value pair
contacts['test'] = 'test@jb51.net'
# Deleting a key/value pair
del contacts['Support']
print 'nThere are %d contacts in the address-bookn' % len(contacts)
for name, address in contacts.items():
print 'Contact %s at %s' % (name, address)
if contacts.has_key('test'):
print "ntest's address is %s" % contacts['test']
输出
$ python using_dict.py Linuxeye's address is linuxeye@jb51.net There are 3 contacts in the address-book Contact Admin at admin@jb51.net Contact test at test@jb51.net Contact Linuxeye at linuxeye@jb51.net test's address is test@jb51.net










