这就是字典

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

使用这个for循环

for keys,values in cars.items():
    print(keys)
    print(values)

它打印以下内容:

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

但是我希望程序像这样打印它:

B
color : 3
speed : 60
A
color : 2
speed : 70

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


当前回答

for car,info in cars.items():
    print(car)
    for key,value in info.items():
        print(key, ":", value)

其他回答

修改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

您可以为此使用json模块。这个模块中的dumps函数将一个JSON对象转换成一个格式正确的字符串,然后可以打印出来。

import json

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

print(json.dumps(cars, indent = 4))

输出如下所示

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

文档还为这个方法指定了一堆有用的选项。

我更喜欢yaml的干净格式:

import yaml
print(yaml.dump(cars))

输出:

A:
  color: 2
  speed: 70
B:
  color: 3
  speed: 60

你有一个嵌套结构,所以你需要格式化嵌套的字典:

for key, car in cars.items():
    print(key)
    for attribute, value in car.items():
        print('{} : {}'.format(attribute, value))

这个打印:

A
color : 2
speed : 70
B
color : 3
speed : 60
for x in cars:
    print (x)
    for y in cars[x]:
        print (y,':',cars[x][y])

输出:

A
color : 2
speed : 70
B
color : 3
speed : 60