我試圖了解如何列印這本字典看起來像這樣:
color: red
name: volvo
但是,輸出正在回傳:
{'color': 'red', 'name': 'volvo'}
uj5u.com熱心網友回復:
使用join()和 f 字串:
>>> d = {'car': 'red', 'name': 'volvo'}
>>> print("\n".join(f"{k}: {v}" for k, v in d.items()))
car: red
name: volvo
或使用for回圈和多個prints:
>>> for k, v in d.items():
... print(f"{k}: {v}")
...
car: red
name: volvo
uj5u.com熱心網友回復:
這是您希望列印字典內容的方式
# You can declare a dictionary like this assigning the keys, to their values
dict_of_cars = {"Color": "Red", "Name": "Volvo"}
# You can iterate through and have the output formatted using a simple for loop
for each_key, each_value in dict_of_cars.items():
print(f"{each_key}: {each_value}")
有關使用 Python 列印字典的更多資訊,請在此處訪問此鏈接,并在此處訪問有關使用printf陳述句的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429004.html
標籤:Python python-3.x 字典
下一篇:字典理解Bigram
