键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
字典是dict类的实例/对象。
结果:
>>>
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
>>>
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
字典是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
>>>