如何在 Python 中逐行打印字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15785719/
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
How to print a dictionary line by line in Python?
提问by Jett
This is the dictionary
这是字典
cars = {'A':{'speed':70,
'color':2},
'B':{'speed':60,
'color':3}}
Using this for loop
使用这个 for loop
for keys,values in cars.items():
print(keys)
print(values)
It prints the following:
它打印以下内容:
B
{'color': 3, 'speed': 60}
A
{'color': 2, 'speed': 70}
But I want the program to print it like this:
但我希望程序像这样打印它:
B
color : 3
speed : 60
A
color : 2
speed : 70
I just started learning dictionaries so I'm not sure how to do this.
我刚开始学习字典,所以我不知道如何做到这一点。
采纳答案by namit
for x in cars:
print (x)
for y in cars[x]:
print (y,':',cars[x][y])
output:
输出:
A
color : 2
speed : 70
B
color : 3
speed : 60
回答by Martijn Pieters
You have a nested structure, so you need to format the nested dictionary too:
您有一个嵌套结构,因此您也需要格式化嵌套字典:
for key, car in cars.items():
print(key)
for attribute, value in car.items():
print('{} : {}'.format(attribute, value))
This prints:
这打印:
A
color : 2
speed : 70
B
color : 3
speed : 60
回答by Scott Olson
for car,info in cars.items():
print(car)
for key,value in info.items():
print(key, ":", value)
回答by Benjamin Hodgson
This will work if you know the tree only has two levels:
如果您知道树只有两个级别,这将起作用:
for k1 in cars:
print(k1)
d = cars[k1]
for k2 in d
print(k2, ':', d[k2])
回答by MrWonderful
A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:
处理任意深度嵌套的字典和列表的更通用的解决方案是:
def dumpclean(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if hasattr(v, '__iter__'):
print k
dumpclean(v)
else:
print '%s : %s' % (k, v)
elif isinstance(obj, list):
for v in obj:
if hasattr(v, '__iter__'):
dumpclean(v)
else:
print v
else:
print obj
This produces the output:
这会产生输出:
A
color : 2
speed : 70
B
color : 3
speed : 60
I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.
我遇到了类似的需求,并为自己开发了一个更强大的功能作为练习。我把它包括在这里,以防它对另一个人有价值。在运行nosetest 时,我还发现能够在调用中指定输出流以便使用sys.stderr 很有帮助。
import sys
def dump(obj, nested_level=0, output=sys.stdout):
spacing = ' '
if isinstance(obj, dict):
print >> output, '%s{' % ((nested_level) * spacing)
for k, v in obj.items():
if hasattr(v, '__iter__'):
print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
dump(v, nested_level + 1, output)
else:
print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
print >> output, '%s}' % (nested_level * spacing)
elif isinstance(obj, list):
print >> output, '%s[' % ((nested_level) * spacing)
for v in obj:
if hasattr(v, '__iter__'):
dump(v, nested_level + 1, output)
else:
print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
print >> output, '%s]' % ((nested_level) * spacing)
else:
print >> output, '%s%s' % (nested_level * spacing, obj)
Using this function, the OP's output looks like this:
使用此函数,OP 的输出如下所示:
{
A:
{
color: 2
speed: 70
}
B:
{
color: 3
speed: 60
}
}
which I personally found to be more useful and descriptive.
我个人认为它更有用和更具描述性。
Given the slightly less-trivial example of:
鉴于稍微不那么平凡的例子:
{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
The OP's requested solution yields this:
OP 要求的解决方案产生以下结果:
test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)
whereas the 'enhanced' version yields this:
而“增强”版本产生了这个:
{
test:
[
{
1: 3
}
]
test3:
{
(1, 2):
[
abc
def
ghi
]
(4, 5): def
}
test2:
[
(1, 2)
(3, 4)
]
}
I hope this provides some value to the next person looking for this type of functionality.
我希望这能为下一个寻找此类功能的人提供一些价值。
回答by kenorb
Check the following one-liner:
检查以下单行:
print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))
Output:
输出:
A
speed : 70
color : 2
B
speed : 60
color : 3
回答by mac13k
pprint.pprint()is a good tool for this job:
pprint.pprint()是这项工作的好工具:
>>> import pprint
>>> cars = {'A':{'speed':70,
... 'color':2},
... 'B':{'speed':60,
... 'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
'speed': 70},
'B': {'color': 3,
'speed': 60}}
回答by kchak
You could use the jsonmodule for this. The dumpsfunction in this module converts a JSON object into a properly formatted string which you can then print.
您可以json为此使用该模块。dumps此模块中的函数将 JSON 对象转换为格式正确的字符串,然后您可以打印该字符串。
import json
cars = {'A':{'speed':70, 'color':2},
'B':{'speed':60, 'color':3}}
print(json.dumps(cars, indent = 4))
The output looks like
输出看起来像
{
"A": {
"color": 2,
"speed": 70
},
"B": {
"color": 3,
"speed": 60
}
}
The documentationalso specifies a bunch of useful options for this method.
该文档还为此方法指定了一堆有用的选项。
回答by Vlad
Modifying MrWonderful code
修改 MrWonderful 代码
import sys
def print_dictionary(obj, ident):
if type(obj) == dict:
for k, v in obj.items():
sys.stdout.write(ident)
if hasattr(v, '__iter__'):
print k
print_dictionary(v, ident + ' ')
else:
print '%s : %s' % (k, v)
elif type(obj) == list:
for v in obj:
sys.stdout.write(ident)
if hasattr(v, '__iter__'):
print_dictionary(v, ident + ' ')
else:
print v
else:
print obj
回答by bpr67
###newbie exact answer desired (Python v3):
###=================================
"""
cars = {'A':{'speed':70,
'color':2},
'B':{'speed':60,
'color':3}}
"""
for keys, values in reversed(sorted(cars.items())):
print(keys)
for keys,values in sorted(values.items()):
print(keys," : ", values)
"""
Output:
B
color : 3
speed : 60
A
color : 2
speed : 70
##[Finished in 0.073s]
"""

