簡體   English   中英

Python:如何打印單個字典值?

[英]Python: how to print individual dictionary values?

我有以下代碼:

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餐廳的類型,位於spoor 18/19。

我希望它是一個for循環,以便打印所有值。

Ps為荷蘭人道歉,但這不應該讓理解代碼變得更加困難。

你可以做點什么

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

我會做:

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開始,您將能夠使用文字字符串插值來更加整齊地執行此操作,可行的方法如下:

for place, data in voorzieningen.items():
    print(f'{place} is of the type {data[type]} and is located at {data[locatie]}')
for key in voorzieningen:
  print("%s is of type %s and is located at %s" % (key, voorzieningen[key]['type'], voorzieningen[key]['location']))
for k, v in voorzieningen.items():
    print('{} is of the type {} and is located at {}'.format(k, v['type'], v['locatie']))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM