如何在Python中迭代 OrderedDict ?
OrderedDict 是保留键插入顺序的子类。 OrderedDict和Dict之间的区别在于,普通Dict不跟踪元素插入的方式,而OrderedDict记住元素插入的顺序。
解释:
Input : original_dict = { ‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4 }
Output: a 1 b 2 c 3 d 4
Input: original_dict = {‘sayantan’:9, ‘sanjoy’:7, ‘suresh’:5, ‘rony’:2}
Output: sayantan 9 sanjoy 7 suresh 5 rony 2
在Python中通过 Ordereddict 执行迭代的步骤:
- 从Python中的集合导入ordereddict 。
- 获取ordereddict的输入。
- 在下面给出的两种方法中的任何一种中遍历ordereddict :
方法#1
遍历ordereddict并打印值。
Python3
# Python code to implement iteration
# over the ordereddict
# import required modules
from collections import OrderedDict
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
# iterating over the ordereddict
for key, value in od.items():
print(key, value)
Python3
# Python code to implement iteration
# over the ordereddict
# import required modules
from collections import OrderedDict
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
# iterating over the ordereddict
for item in od.items():
print(*item)
Python3
# Python code to implement iteration
# over the ordereddict
# import required modules
from collections import OrderedDict
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
# iterating through the enumerate objects
for i, (key, value) in enumerate(od.items()):
print(key, value)
输出 :
a 1
b 2
c 3
d 4
上面的代码也可以写成——
蟒蛇3
# Python code to implement iteration
# over the ordereddict
# import required modules
from collections import OrderedDict
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
# iterating over the ordereddict
for item in od.items():
print(*item)
输出 :
a 1
b 2
c 3
d 4
方法#2
遍历枚举对象并打印值。 enumerate() 方法是一种向可迭代对象添加计数器并以枚举对象的形式返回值的方法。
蟒蛇3
# Python code to implement iteration
# over the ordereddict
# import required modules
from collections import OrderedDict
# create dictionary
od = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
# iterating through the enumerate objects
for i, (key, value) in enumerate(od.items()):
print(key, value)
输出:
a 1
b 2
c 3
d 4