簡體   English   中英

在 python 字典中,如何顯示字典條目的鍵和值的內容?

[英]In a python dictionary how can I display the content of the key and value of the dictionary entry?

city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
print(city)
for key in city:
    print(city)

下面我為您提供兩種選擇。 這個可迭代對象也稱為字典而不是目錄,盡管這可能是一個錯字,但我想指出這一點。

選項1 您可以使用dict.items dict.items()

city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
for k,v in city.items():
    print(f'key: {k}')
    print(f'value: {v}')

選項二use dict[key]

city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
for k in city:
    print(f'key: {k}')
    print(f'value: {city[k]}')

output

key: New York
value: 2
key: Minnespolis
value: 2
key: thing 
value: 3

您的意思是通過鍵訪問值嗎?

city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
print(city)
for key in city:
    print(city[key])

暫無
暫無

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

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