如何在python中打印字典的键值对

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

key1 \t value1
key2 \t value2

我想我可以这样做:

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

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

1043144 次浏览
for key, value in d.iteritems():
print key, '\t', value

或者,对于Python 3:

for k,v in dict.items():
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

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()返回一个(键,值)元组列表,而d.iteritems()返回一个提供相同元组的迭代器:

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

简单介绍一下字典

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

打印键值,方法一

for x in d.keys():
print(x +" => " + d[x])

另一种方法

for key,value in d.items():
print(key + " => " + value)

你可以使用iter获取密钥

>>> list(iter(d))
['a', 'b']

你可以使用get(key, [value])获取字典key的值:

d.get('a')
'apple'

如果key不存在于字典中,当给出默认值时,将返回value。

d.get('c', 'Cat')
'Cat'

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

>>> 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]

你可以通过在字典上调用项目()来访问你的键和/或值。

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

如果你想通过dict键排序输出,你可以使用集合包。

import collections
for k, v in collections.OrderedDict(sorted(d.items())).items():
print(k, v)

它适用于python 3

一本简单的字典:

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

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

打印键值对,例如:

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

如果你正在寻找漂亮的打印字典,请查看丰富的:

from rich import print


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


print(prices)

enter image description here