加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python中实现按顺序遍历字典

发布时间:2020-12-20 10:27:37 所属栏目:Python 来源:网络整理
导读:第一种方法: import collectionsd = 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(): prin

第一种方法:

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,3)])
for 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读