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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26660654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:50:10  来源:igfitidea点击:

How do I print the key-value pairs of a dictionary in python

pythondictionary

提问by oaklander114

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

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

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.

但显然这不是它的方式keys()values()也不要争论。

采纳答案by chepner

Your existing code just needs a little tweak. iisthe key, so you would just need to use it:

您现有的代码只需要一点点调整。i关键,所以你只需要使用它:

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:

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

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.

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

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

回答by Mauro Baraldi

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

回答by Patrick Beeson

Or, for Python 3:

或者,对于 Python 3:

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

回答by Irshad Bhat

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

回答by Hackaholic

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

您可以使用 iter

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

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

您可以使用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'

回答by SuperNova

In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'

除了已经提到的方法..可以使用'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

或使用 itemgetter

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

回答by goulon

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

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

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

回答by paolof89

If you want to sortthe output by dict key you can use the collectionpackage.

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

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

It works on python 3

它适用于python 3

回答by Fouad Boukredine

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

要在 Python 3 中打印特定的 (key, value) 对(在本例中为索引 1 的对):

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

回答by Nara Begnini

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)

(但是,由于之前没有人提出过类似的建议,我怀疑这不是一个好习惯)