Python 遍历字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48585577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate Over Dictionary
提问by ZrSiO4
The two setups using print(i, j)
and print(i)
return the same result. Are there cases when one
should be used over the other or is it correct to use them interchangeably?
使用print(i, j)
和print(i)
返回相同结果的两个设置。是否存在一种情况应优先使用另一种情况,或者交替使用它们是否正确?
desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}
for i, j in desc.items():
print(i, j)
for i in desc.items():
print(i)
for i, j in desc.items():
print(i, j)[1]
for i in desc.items():
print(i)[1]
回答by Artier
Both are different if remove parenthesis in print because you are using python 2X
如果删除打印中的括号,则两者都不同,因为您使用的是 python 2X
desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}
for i, j in desc.items():
print i, j
for i in desc.items():
print i
output
输出
county Boyd
city Monowi
state Nebraska
pop 1
('county', 'Boyd')
('city', 'Monowi')
('state', 'Nebraska')
('pop', 1)
回答by A.B.
In Python 3, print(i, j)
and print(i)
does notreturn the same result.
在Python 3,print(i, j)
而print(i)
不会不返回相同的结果。
print(i, j)
prints the key i
followed by it's value j
print(i, j)
打印键i
后跟它的值j
print(i)
prints a tuple containing the dictionary key followed by its value
print(i)
打印包含字典键后跟其值的元组
回答by PJ.Hades
items()
returns a view object which allows you to iterate over the (key, value)
tuples. So basically you can just manipulate them as what you do with tuples. The documentmay help:
items()
返回一个视图对象,它允许您遍历(key, value)
元组。所以基本上你可以像处理元组一样操作它们。该文件可能有助于:
iter(dictview) Return an iterator over the keys, values or items (represented as tuples > of (key, value)) in the dictionary.
iter(dictview) 返回字典中键、值或项(表示为元组 > of (key, value))的迭代器。
Also I think print(i, j)[1]
would result in error in Python 3 since print(i, j)
returns None
.
另外我认为print(i, j)[1]
会导致 Python 3 中的错误,因为print(i, j)
return None
。