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

key1 \t value1
key2 \t value2

我想我可以这样做:

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

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


当前回答

一本简单的字典:

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'))

其他回答

字典:

d={'key1':'value1','key2':'value2','key3':'value3'}

另一个单线解决方案:

print(*d.items(), sep='\n')

输出:

('key1', 'value1')
('key2', 'value2')
('key3', 'value3')

(但是,由于之前没有人建议这样做,我怀疑这不是一个好的实践)

一本简单的字典:

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'))

打印键值对,例如:

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

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
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
...     print kv[0],'\t',kv[1]
... 
a   1
c   3
b   2