标签:
dictionary,字典,无序的列表——用于查询表的制作
dictionary的基本操作:
# -*- coding: utf-8 -*- life = { # 创建dictionary ‘baby‘: ‘0-3‘, ‘little_child‘: ‘4-7‘, ‘child‘: ‘8-12‘ } print life[‘baby‘] # dict中元素的输出和列表相似 life[‘teenage‘] = ‘13-17‘ # 元素的添加 life[‘adult‘] = ‘18-60‘ print life del life[‘adult‘] # 元素的删除 print life print "The progress of life is %s,%s,%s." % ( life[‘baby‘], life[‘little_child‘], life[‘child‘] )
———————————————————————华丽——————————————的————————————————分割线——————————————————————————
dictionary的函数:
1. dict.items()
for lives,period in life.items(): # dict.items的用法——创建lives和period两个变量,分别用作life这个字典中“:”前后的变量名 print "Age between %s belongs to %s." % (period, life) print lives,period # .items()语句中创建的是全局变量!
2. dict.get()
period_ = life.get("Old", "Not exist.") # get函数得到的第一个参数在dict中存在,返回它的值;否则返回逗号之后的值 print "The new period is ", period_ # get得到的值并不会赋值到dict中,仅临时存在 print life period__ = life.get(‘babies‘, ‘0-4‘) print period__,"\n",life
标签:
原文地址:http://www.cnblogs.com/nopear/p/5772723.html