Home > Mobile >  How to format the way dictionaries print in Python?
How to format the way dictionaries print in Python?

Time:02-19

I am trying to understand how to print this dictionary to look something like this:

color: red
name: volvo

However, the output is returning:

{'color': 'red', 'name': 'volvo'}

CodePudding user response:

Using join() and an f-string:

>>> d = {'car': 'red', 'name': 'volvo'}
>>> print("\n".join(f"{k}: {v}" for k, v in d.items()))
car: red
name: volvo

or with a for loop and multiple prints:

>>> for k, v in d.items():
...     print(f"{k}: {v}")
...
car: red
name: volvo

CodePudding user response:

This is the way you are looking to print your dictionaries content

# 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}")

For more information on printing dictionaries with Python, visit this link here, and more information on using printf statements here.

  • Related