我有以下代码:
voorzieningen = {
"NS-service- en verkooppunt": {"type:": "verkoop- en reisinformatie", "locatie": "spoor 11/12"},
"Starbucks": {"type": "Winkels en restaurants", "locatie": "spoor 18/19"},
"Smeulers": {"type": "Winkels en restaurants", "locatie": "spoor 5/6"},
"Kaartautomaat": {"type": "Verkoop- en reisinformatie", "locatie": "spoor 1"},
"Toilet": {"type": "Extra voorziening", "locatie": "spoor 4"}
}
def voorzieningen_op_utrecht():
for voorziening in voorzieningen:
print(voorziening)
voorzieningen_op_utrecht()
我想得的是以下内容:
<First value> "is of the type " <second value> "and is located at" <third value>
例如:
星巴克是Winkels en餐厅的类型,位于spoor 18/19。
我希望它是一个for循环,以便打印所有值。
P.S。为荷兰人道歉,但这不应该让理解代码变得更加困难。
答案 0 :(得分:3)
您可以执行类似
的操作for key, value in voorzieningen.items():
print('{} is of the type {} and is located at {}'.format(key, value['type'], value['locatie']))
示例输出
NS-service- en verkooppunt属于verkoop-en reisinformatie,位于spoor 11/12
Kaartautomaat属于Verkoop-en reisinformatie,位于spoor 1
Smeulers属于Winkels en餐厅,位于spoor 5/6
星巴克是Winkels餐厅的类型,位于spoor 18/19
厕所属于Extra voorziening类型,位于spoor 4
答案 1 :(得分:3)
我愿意:
template = '{place} is of the type {data[type]} and is located at {data[locatie]}'
for place, data in voorzieningen.items():
print(template.format(place=place, data=data))
这样可以在格式字符串中保留大量信息,从而更轻松地验证您是否做了正确的事情。但是,我得到了输出:
Starbucks is of the type Winkels en restaurants and is located at spoor 18/19
Smeulers is of the type Winkels en restaurants and is located at spoor 5/6
Traceback (most recent call last):
File "<pyshell#9>", line 2, in <module>
print(template.format(place=place, data=data))
KeyError: 'type'
因为其中一个密钥有'type:'
而非'type'
;注意未经过清理的输入数据!
从Python 3.6开始,您将能够使用literal string interpolation更加整洁地执行此操作,可行的方式如下:
for place, data in voorzieningen.items():
print(f'{place} is of the type {data[type]} and is located at {data[locatie]}')
答案 2 :(得分:1)
for key in voorzieningen:
print("%s is of type %s and is located at %s" % (key, voorzieningen[key]['type'], voorzieningen[key]['location']))
答案 3 :(得分:1)
for k, v in voorzieningen.items():
print('{} is of the type {} and is located at {}'.format(k, v['type'], v['locatie']))