数据结构---字典

字典:

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。

键:唯一、不可变的对象(比如字符串)。

键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

记住字典中的键/值对没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序

字典是dict类的实例/对象。

例python代码使用字典:

#!/usr/bin/python
# Filename: using_dict.py
# 'ab' is short for 'a'ddress'b'ook
ab ={ 'Swaraoop':'[email protected]', 
    'Larry':'[email protected]',
    'Matsumoto':'[email protected]',
    'Spammer':'[email protected]'
    }
print "Swaroop's address is %s" % ab['Swaraoop']
#Adding a key/value pair
ab['Guido']='[email protected]'
#Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n'%len(ab)
#我们使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。
我们抓取这个对,然后分别赋给for..in循环中的变量name和address然后在for-块中打印这些值。
我们可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。你可以使用help(dict)来查看dict类的完整方法列表。
for name,address in ab.items():
    print 'Contact %s at %s'%(name,address)
if 'Guido' in ab:    #Or ab.has_key('Guido')
    print "\n Guido's address is %s"%ab['Guido']
输出
[root@losnau python]# python using_dict.py
Swaroop's address is [email protected]

There are 4 contacts in the address-book

Contact Matsumoto at [email protected]
Contact Larry at [email protected]
Contact Swaraoop at [email protected]
Contact Guido at [email protected]

Guido's address is [email protected]

猜你喜欢

转载自blog.csdn.net/jingzhi111/article/details/80601418