在字典中循环时,关键字和对应的值可以使用 items() 方法同时解读出来。
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print k, v ... gallahad the pure robin the brave
字典的格式以{key:value}的格式来定义
比如
a = {'name':'xiaoming','age':23}
字典支持嵌套
下面介绍的操作方法用到的例子是:
a = {'name':'xiaoming','age':23}
Python的字典的items(), keys(), values()都返回一个list
>>> dict = { 1 : 2, 'a' : 'b', 'hello' : 'world' }
>>> dict.values()
['b', 2, 'world']
>>> dict.keys()
['a', 1, 'hello']
>>> dict.items()
[('a', 'b'), (1, 2), ('hello', 'world')]
>>>
遍历字典的几种方法:
#!/usr/bin/python dict={"a":"apple","b":"banana","o":"orange"} print "##########dict######################" for i in dict: print "dict[%s]=" % i,dict[i] print "###########items#####################" for (k,v) in dict.items(): print "dict[%s]=" % k,v print "###########iteritems#################" for k,v in dict.iteritems(): print "dict[%s]=" % k,v print "###########iterkeys,itervalues#######" for k,v in zip(dict.iterkeys(),dict.itervalues()): print "dict[%s]=" % k,v
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到。
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe
同时循环两个或更多的序列,可以使用 zip() 整体解读。
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your %s? It is %s.' % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.