这就是字典

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

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


当前回答

###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]
"""

其他回答

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

如果你知道树只有两层,这是可行的:

for k1 in cars:
    print(k1)
    d = cars[k1]
    for k2 in d
        print(k2, ':', d[k2])

我认为列表理解是最干净的方法:

mydict = {a:1, b:2, c:3}

[(print("key:", key, end='\t'), print('value:', value)) for key, value in mydict.items()]

这是我对这个问题的解决办法。我认为它在方法上是相似的,但比其他一些答案更简单。它还允许任意数量的子字典,并且似乎适用于任何数据类型(我甚至在一个以函数为值的字典上测试了它):

def pprint(web, level):
    for k,v in web.items():
        if isinstance(v, dict):
            print('\t'*level, f'{k}: ')
            level += 1
            pprint(v, level)
            level -= 1
        else:
            print('\t'*level, k, ": ", v)
###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]
"""