Python中实现按顺序遍历字典


第一种方法:

import collections

d = collections.OrderedDict([('a',1),('b',2),('c',3)])
'''
或者把上面的那一行改成:
    d = collections.OrderedDict()
    d['a'] = 1
    d['b'] = 2 
    d['c'] = 3
'''
for k,v in d.items():
    print(k,v)

输出结果:
        a 1
        b 2
        c 3

第二种方法:

from collections import OrderedDict  

d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
for k,v in d.items():
    print(k,v)

输出结果:
        a 1
        b 2
        c 3

第三种方法:

d = {'a':1, 'b':2, 'c':3}
e = ['a', 'b', 'c']
for i in range(3):
    print( str(e[i]) + " " + str(d[e[i]]) )
    # 这里的键值是 int 型数字,需要 str() 转一下
输出结果:
        a 1
        b 2
        c 3

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM