ptyhon中遍历数据字典的方式详解
python遍历字典几种方式
举例说明如下:
#!usr/bin/env Python #coding=UTF-8 mydic = {'zhangsan':'28', 'lisi':'25', 'wangwu':'27'} print '数据字典为:',mydic print '-----------dict-------------' for d in mydic: print "%s:%s" %(d, mydic[d]) #print '%s,%s' %(mydic[d],d) #print [('{}:{}'.format(mydic[d],d))] print '-----------item-------------' for (key,value) in mydic.items(): #返回字典列表 print '%s:%s' %(key, value) #效率最高 print '------------iteritems---------' for (key,value) in mydic.iteritems(): #返回一个迭代器对象 print '%s:%s' % (key, value) #很古老的方式:不推荐使用 print '---------iterkeys---------------' for key in mydic.iterkeys(): print '%s:%s' % (key, mydic[key]) print '------------iterkeys, itervalues----------' for key,value in zip(mydic.iterkeys(), mydic.itervalues()): print '%s:%s' % (key, value) #运行结果如下: 数据字典为: {'lisi': '25', 'zhangsan': '28', 'wangwu': '27'} -----------dict------------- lisi:25 zhangsan:28 wangwu:27 -----------item------------- lisi:25 zhangsan:28 wangwu:27 ------------iteritems--------- lisi:25 zhangsan:28 wangwu:27 ---------iterkeys--------------- lisi:25 zhangsan:28 wangwu:27 ------------iterkeys, itervalues---------- lisi:25 zhangsan:28 wangwu:27 #遍历字典,分别打印key,value,key:value dict = {'lisi': '25', 'zhangsan': '28', 'wangwu': '27'} #1.遍历key for k in dict.keys(): print('key = {}'.format(k)) #2.遍历value for v in dict.values(): print('values = {}'.format(v)) #3.遍历字典 #items()能够得到一个关于字典的列表,列表中的元素是由字典中的键和值组成的元组 for v,k in dict.items(): print('{v}:{k}'.format(v = v, k = k))