问题描述
我想从python字典输出我的键值对:
I want to output my key value pairs from a python dictionary as such:
key1 \t value1
key2 \t value2
我以为我可以这样做:
for i in d:
print d.keys(i), d.values(i)
但显然这不是如此,因为 keys()
和 values()
不要参数...
but obviously that's not how it goes as the keys()
and values()
don't take an argument...
谢谢。
推荐答案
您现有的代码只需要稍微调整一下。 我
是关键,所以你只需要使用它:
Your existing code just needs a little tweak. i
is the key, so you would just need to use it:
for i in d:
print i, d[i]
你也可以得到一个包含键和值的迭代器。在Python 2中, d.items()
返回(key,value)元组的列表,而 d.iteritems()
返回一个提供相同的迭代器:
You can also get an iterator that contains both keys and values. In Python 2, d.items()
returns a list of (key, value) tuples, while d.iteritems()
returns an iterator that provides the same:
for k, v in d.iteritems():
print k, v
在Python 3中, d.items()
返回迭代器;要获得列表,您需要自己将迭代器传递给 list()
。
In Python 3, d.items()
returns the iterator; to get a list, you need to pass the iterator to list()
yourself.
for k, v in d.items():
print(k, v)
这篇关于如何在python中打印字典的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!