相关疑难解决方法(0)

使用'for'循环迭代字典

我对以下代码感到有点困惑:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print key, 'corresponds to', d[key]
Run Code Online (Sandbox Code Playgroud)

我不明白的是这个key部分.Python如何识别它只需要从字典中读取密钥?keyPython中是一个特殊的词吗?或者它只是一个变量?

python dictionary python-2.7

2901
推荐指数
13
解决办法
411万
查看次数

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

这是字典

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)

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

python printing dictionary

146
推荐指数
8
解决办法
57万
查看次数

标签 统计

dictionary ×2

python ×2

printing ×1

python-2.7 ×1