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

key1 \t value1
key2 \t value2

我想我可以这样做:

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

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


当前回答

打印键值对,例如:

players = {
     'lebron': 'lakers',
     'giannis':   'milwakee bucks',
     'durant':  'brooklyn nets',
     'kawhi':   'clippers',    
}

对于player,在players.items()中的club:

print(f"\n{player.title()} is the leader of {club}")

上面的代码,键值对:

 'lebron': 'lakers', - Lebron is key and lakers is value

对于循环-在dictionary.item()中指定键和值:

现在打印(玩家名是俱乐部队长)。

输出为:

#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers

其他回答

>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
...     print kv[0],'\t',kv[1]
... 
a   1
c   3
b   2

或者,对于Python 3:

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

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

一本简单的字典:

x = {'X':"yes", 'Y':"no", 'Z':"ok"}

在Python 3中打印一个特定的(键,值)对(本例中是索引1处的pair):

for e in range(len(x)):
    print(([x for x in x.keys()][e], [x for x in x.values()][e]))

输出:

('X', 'yes')
('Y', 'no')
('Z', 'ok')

下面是打印元组中所有对的一行程序:

print(tuple(([x for x in x.keys()][i], [x for x in x.values()][i]) for i in range(len(x))))

输出:

(('X', 'yes'), ('Y', 'no'), ('Z', 'ok'))

除了已经提到的方法之外。可以使用" 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]