码迷,mamicode.com
首页 > 编程语言 > 详细

Python中实现按顺序遍历字典

时间:2019-09-30 14:44:20      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:items   bsp   实现   dict   code   顺序   item   print   需要   

第一种方法:

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

 

Python中实现按顺序遍历字典

标签:items   bsp   实现   dict   code   顺序   item   print   需要   

原文地址:https://www.cnblogs.com/fousor/p/11612491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!