我想从python字典中输出我的键值对,如下所示:

key1 \t value1
key2 \t value2

我想我可以这样做:

for i in d:
    print d.keys(i), d.values(i)

但显然不是这样的,因为keys()和values()不带参数。


当前回答

您可以通过在字典上调用items()来访问键和/或值。

for key, value in d.iteritems():
    print(key, value)

其他回答

或者,对于Python 3:

for k,v in dict.items():
    print(k, v)

您可以通过在字典上调用items()来访问键和/或值。

for key, value in d.iteritems():
    print(key, value)

Python 2和Python 3

I是键,所以你只需要使用它:

for i in d:
    print i, d[i]

Python 3

D.items()返回迭代器;要获得一个列表,需要自己将迭代器传递给list()。

for k, v in d.items():
    print(k, v)

Python 2

你可以得到一个同时包含键和值的迭代器。D.items()返回一个(key, value)元组列表,而d.iteritems()返回一个提供相同元组的迭代器:

for k, v in d.iteritems():
    print k, v

除了已经提到的方法之外。可以使用" viewitems " " viewkeys " " viewvalues "

>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]

Or

>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]

或者使用itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items())     ####  for keys
['323', '332']
>>> map(itemgetter(1), dd.items())     ####  for values
['3323', 232]

如果你正在寻找漂亮的印刷字典,看看Rich:

from rich import print

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3,
    "strawberry": 1,
    "blueberry": 0.5,
    "mango": 4.5
}

print(prices)