Python中 dict.items() 和 dict.iteritems() 的区别
dict.items()
和dict.iteriteams()
almots 做同样的事情,但它们之间有细微的差别——
- dict.items():以(key, value)元组对的形式返回字典列表的副本,是(Python v3.x)版本,存在于(Python v2.x)版本中。
- dict.iteritems():以(键,值)元组对的形式返回字典列表的迭代器。这是一个(Python v2.x)版本,在(Python v3.x)版本中被省略了。
对于 Python2.x:
示例-1
# Python2 code to demonstrate
# d.iteritems()
d ={
"fantasy": "harrypotter",
"romance": "me before you",
"fiction": "divergent"
}
# every time you run the object address keeps changes
print d.iteritems()
输出:
要打印字典项,请使用for()
循环来划分对象并打印它们
示例 2
# Python2 code to demonstrate
# d.iteritems()
d ={
"fantasy": "harrypotter",
"romance": "me before you",
"fiction": "divergent"
}
for i in d.iteritems():
# prints the items
print(i)
输出:
('romance', 'me before you')
('fantasy', 'harrypotter')
('fiction', 'divergent')
如果我们尝试在Python v2.x 中运行 dict.items( ) ,它会运行为dict.items()存在于 v2.x 中。
示例 3
# Python2 code to demonstrate
# d.items()
d ={
"fantasy": "harrypotter",
"romance": "me before you",
"fiction": "divergent"
}
# places the tuples in a list.
print(d.items())
# returns iterators and never builds a list fully.
print(d.iteritems())
输出:
[(‘romance’, ‘me before you’), (‘fantasy’, ‘harrypotter’), (‘fiction’, ‘divergent’)]
对于 Python3:
示例-1
# Python3 code to demonstrate
# d.items()
d ={
"fantasy": "harrypotter",
"romance": "me before you",
"fiction": "divergent"
}
# saves as a copy
print(d.items())
输出:
dict_items([(‘fantasy’, ‘harrypotter’), (‘fiction’, ‘divergent’), (‘romance’, ‘me before you’)])
如果我们尝试在Python v3.x 中运行dict.iteritems()
,我们将遇到错误。
示例 2
# Python3 code to demonstrate
# d.iteritems()
d ={
"fantasy": "harrypotter",
"romance": "me before you",
"fiction": "divergent"
}
print("d.items() in (v3.6.2) = ")
for i in d.items():
# prints the items
print(i)
print("\nd.iteritems() in (v3.6.2)=")
for i in d.iteritems():
# prints the items
print(i)
输出:
d.items() in (v3.6.2) =
('fiction', 'divergent')
('fantasy', 'harrypotter')
('romance', 'me before you')
d.iteritems() in (v3.6.2)=
Traceback (most recent call last):
File "/home/33cecec06331126ebf113f154753a9a0.py", line 19, in
for i in d.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'