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

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

我想像这样从python字典输出我的键值对:

key1 \t value1
key2 \t value2

我以为我可以这样做:

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

但是很明显,这不是keys()values()不参数的方式。

I want to output my key value pairs from a python dictionary as such:

key1 \t value1
key2 \t value2

I thought I could maybe do it like this:

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

but obviously that’s not how it goes as the keys() and values() don’t take an argument.


回答 0

您现有的代码只需进行一些调整。i 关键,因此您只需要使用它:

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

您还可以获得包含键和值的迭代器。在Python 2中,d.items()返回(键,值)元组的列表,同时d.iteritems()返回提供相同值的迭代器:

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

在Python 3中,d.items()返回迭代器;要获得列表,您需要将迭代器传递给list()自己。

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

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]

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

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)

回答 1

字典简介

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

d.get('a')
'apple'

如果字典中不存在键,则在给定默认值时将返回值。

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

A little intro to dictionary

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

Print keys,values method one

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

Another method

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

You can get keys using iter

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

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

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

回答 2

或者,对于Python 3:

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

Or, for Python 3:

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

回答 3

词典:

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

另一种解决方案:

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

输出:

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

(但是,由于以前没有人提出过这样的建议,所以我认为这不是好习惯)

The dictionary:

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

Another one line solution:

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

Output:

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

(but, since no one has suggested something like this before, I suspect it is not good practice)


回答 4

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

回答 5

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

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

You can access your keys and/or values by calling items() on your dictionary.

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

回答 6

如果要按dict键对输出进行排序,则可以使用收集包。

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

它适用于python 3

If you want to sort the output by dict key you can use the collection package.

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

It works on python 3


回答 7

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

回答 8

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

In addition to ways already mentioned.. can use ‘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]

or using itemgetter

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

回答 9

一个简单的字典:

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

要在Python 3中打印特定的(键,值)对(在此示例中为索引1的对):

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

A simple dictionary:

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

To print a specific (key, value) pair in Python 3 (pair at index 1 in this example):

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

Output:

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

Here is a one liner solution to print all pairs in a tuple:

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

Output:

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