如何用Python按顺序遍历字典的键值对?

2026-06-11 06:291阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计227个文字,预计阅读时间需要1分钟。

如何用Python按顺序遍历字典的键值对?

一种方法:使用`collections.OrderedDict`创建有序字典,直接赋值:

pythonimport collectionsd=collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)])

或者使用字典推导式:

pythond=collections.OrderedDict({'a': 1, 'b': 2, 'c': 3})

第一种方法:

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按顺序遍历字典的键值对?

本文共计227个文字,预计阅读时间需要1分钟。

如何用Python按顺序遍历字典的键值对?

一种方法:使用`collections.OrderedDict`创建有序字典,直接赋值:

pythonimport collectionsd=collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)])

或者使用字典推导式:

pythond=collections.OrderedDict({'a': 1, 'b': 2, 'c': 3})

第一种方法:

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按顺序遍历字典的键值对?