如何在Python中逐行打印字典?

Jet*_*ett 146 python printing dictionary

这是字典

cars = {'A':{'speed':70,
        'color':2},
        'B':{'speed':60,
        'color':3}}
Run Code Online (Sandbox Code Playgroud)

用这个 for loop

for keys,values in cars.items():
    print(keys)
    print(values)
Run Code Online (Sandbox Code Playgroud)

它打印以下内容:

B
{'color': 3, 'speed': 60}
A
{'color': 2, 'speed': 70}
Run Code Online (Sandbox Code Playgroud)

但我希望程序打印出来像这样:

B
color : 3
speed : 60
A
color : 2
speed : 70
Run Code Online (Sandbox Code Playgroud)

我刚开始学习字典,所以我不知道该怎么做.

nam*_*mit 130

for x in cars:
    print (x)
    for y in cars[x]:
        print (y,':',cars[x][y])
Run Code Online (Sandbox Code Playgroud)

输出:

A
color : 2
speed : 70
B
color : 3
speed : 60
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是旧的,但我认为值得一提的是,如果cars [x]是整数,这不起作用.这不是OP所要求的,所以我只是为任何偶然发现它的人说这是一个全面的解决方案. (11认同)

kch*_*hak 99

您可以使用该json模块.dumps此模块中的函数将JSON对象转换为格式正确的字符串,然后您可以打印该字符串.

import json

cars = {'A':{'speed':70, 'color':2},
        'B':{'speed':60, 'color':3}}

print(json.dumps(cars, indent = 4))
Run Code Online (Sandbox Code Playgroud)

输出看起来像

{
    "A": {
        "color": 2,
        "speed": 70
    },
    "B": {
        "color": 3,
        "speed": 60
    }
}

文档还为此方法指定了许多有用的选项.

  • 是的,字典的内容必须可序列化为json,但是,此处提供的输出比pprint.PrettyPrinter产生的输出更干净(例如,人类可读)。特别是在一致缩进和丢弃字符串前缀(例如u'foo')方面。 (2认同)

MrW*_*ful 84

处理任意深度嵌套的dicts和列表的更通用的解决方案是:

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
Run Code Online (Sandbox Code Playgroud)

这会产生输出:

A
color : 2
speed : 70
B
color : 3
speed : 60
Run Code Online (Sandbox Code Playgroud)

我遇到了类似的需求,并为自己开发了一个更强大的功能.我把它包括在这里,以防它对另一个人有价值.在运行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)
Run Code Online (Sandbox Code Playgroud)

使用此函数,OP的输出如下所示:

{
   A:
   {
      color: 2
      speed: 70
   }
   B:
   {
      color: 3
      speed: 60
   }
}
Run Code Online (Sandbox Code Playgroud)

我个人发现它更有用和描述性.

鉴于稍微不那么简单的例子:

{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
Run Code Online (Sandbox Code Playgroud)

OP的请求解决方案产生了这样的结果:

test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)
Run Code Online (Sandbox Code Playgroud)

而'增强'版本产生了这个:

{
   test:
   [
      {
         1: 3
      }
   ]
   test3:
   {
      (1, 2):
      [
         abc
         def
         ghi
      ]
      (4, 5): def
   }
   test2:
   [
      (1, 2)
      (3, 4)
   ]
}
Run Code Online (Sandbox Code Playgroud)

我希望这为寻找此类功能的下一个人提供了一些价值.

  • 如果格式不是过于严格,也可以使用'print json.dumps(obj,indent = 3)'.这给出了大多数结构的合理表示,尽管由于使用元组作为关键字,它在我的不太重要的例子中扼杀了(在我的环境中)... (10认同)
  • 为什么不在这里使用[`pprint.pprint()`](https://docs.python.org/2/library/pprint.html#pprint.pprint)? (5认同)

Mar*_*ers 29

您有嵌套结构,因此您还需要格式化嵌套字典:

for key, car in cars.items():
    print(key)
    for attribute, value in car.items():
        print('{} : {}'.format(attribute, value))
Run Code Online (Sandbox Code Playgroud)

这打印:

A
color : 2
speed : 70
B
color : 3
speed : 60
Run Code Online (Sandbox Code Playgroud)


mac*_*13k 22

正如Martijn Pieters在上述评论中提到的那样,PrettyPrint是这项工作的好工具:

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是迄今为止最简单和最好的解决方案,因为它还可以在嵌套在 *dict* 中时处理 *sets、tuples* 和 *lists*。 (3认同)

giz*_*ole 9

我更喜欢干净的格式yaml

import yaml
print(yaml.dump(cars))
Run Code Online (Sandbox Code Playgroud)

输出:

A:
  color: 2
  speed: 70
B:
  color: 3
  speed: 60
Run Code Online (Sandbox Code Playgroud)

  • 您必须先“pip install PyYAML”。 (2认同)
  • 与上面的“pprint”示例不同,当字典中嵌套有列表时,这似乎会中断。 (2认同)

Sco*_*son 7

for car,info in cars.items():
    print(car)
    for key,value in info.items():
        print(key, ":", value)
Run Code Online (Sandbox Code Playgroud)


Ben*_*son 5

如果您知道树只有两个级别,这将起作用:

for k1 in cars:
    print(k1)
    d = cars[k1]
    for k2 in d
        print(k2, ':', d[k2])
Run Code Online (Sandbox Code Playgroud)