Python:如何打印单个字典值?

Python:如何打印单个字典值?,python,for-loop,dictionary,Python,For Loop,Dictionary,我有以下代码: 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 restaur

我有以下代码:

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餐厅类型,位于斯波尔18/19。

我希望它是一个for循环,以便打印所有值


请注意,我为荷兰人道歉,但这不应使理解代码变得更困难。

您可以这样做

for key, value in voorzieningen.items():
    print('{} is of the type {} and is located at {}'.format(key, value['type'], value['locatie']))
您的示例的输出

NS服务-en Verkoopport属于verkoop-en Reissinformatie类型,位于spoor 11/12
KaartAutomat属于Verkoop-en Reissinformatie类型,位于Spor 1
Smeulers属于Winkels en餐厅类型,位于Spor 5/6
星巴克属于Winkels en餐厅类型,位于斯波尔18/19
卫生间为额外通风型,位于4号门处

我会:

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'

“第一”、“第二”和“第三”没有意义,字典不能保证顺序。您是否研究过str.format?另外,请注意,其中一个键是
'type:'
而不是
'type'
。将该键移动到格式字符串中可能更整洁-
'{0}属于类型{1[type]}并且位于{1[locatie]}'
。这使得在字符串变长时更容易确保正确的东西位于正确的位置。此时,C风格的
%
字符串格式有点过时!夏普的名字和行动:)完美!非常感谢你。
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'
for place, data in voorzieningen.items():
    print(f'{place} is of the type {data[type]} and is located at {data[locatie]}')