python学习之路-字典

1、字典

  • 字典其实就是key-value对
  • 例子:(python简明教程)
#!/usr/bin/python
# Filename: using_dict.py

# 'ab' is short for 'a'ddress'b'ook

ab = {       'Swaroop'   : '[email protected]',
             'Larry'     : '[email protected]',
             'Matsumoto' : '[email protected]',
             'Spammer'   : '[email protected]'
     }

print "Swaroop's address is %s" % ab['Swaroop']

# 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)
for name, address in 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']

  

  • 结果:
$ python using_dict.py
Swaroop's address is [email protected]

There are 4 contacts in the address-book

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

Guido's address is [email protected]

  

  • items方法用于返回一个元组的列表,每个列表中都有键和值,如上面的for循环遍历

  • in方法或者has_key方法可以检验这个键是否存在

  • %s 它的含义是“这里将被替换成一个新的字符串”
  • 字符串中的%后面会附带一个字母,代表着用来替换的变量的类型,比如说%d代表着你将替换到此处的变量是一个整数,而%s代表着一个字符串

猜你喜欢

转载自www.cnblogs.com/qing-er/p/8904762.html