Home > Enterprise >  How to print a dictionary on separate lines
How to print a dictionary on separate lines

Time:10-26

I am attempting to use the following approach to printing the contents of a dictionary which consists of a key and multiple values for each item.


for target in items:

   print("{0}:{1}".format(target, items[target]))

The current output is the "raw" dictionary contents on a single line and I'm wondering how to print the values on separate lines instead. I have been able to print the first key as desired, but not the subsequent values.

CodePudding user response:

In order to print out all dictionary keys and values you will need to iterate the full dictionary. This is easiest to do with the .items() method . then to print the values on their own line you would need to iterate those as well.

for key, values in items.items():
    print(key, ":")
    for value in values:
        # print("  ", value) # <-- it would be more readable with some indentation 
        print(value)    # or without indentation

CodePudding user response:

If you just want more readable output I would suggest looking at pprint. You can add formatting options, but this is a basic example:

from pprint import pprint

items = {'first': {'a': 1, 'b': 2, 'c': 3},'second': {'a': 1, 'b': 2, 'c': 3}, 'third': {'a': 1, 'b': 2, 'c': 3},'fourth': {'a': 1, 'b': 2, 'c': 3}}

pprint(items)

Otherwise, you can use print in a for loop like this:

example = {'first': {'a': 1, 'b': 2, 'c': 3},'second': {'a': 1, 'b': 2, 'c': 3}, 'third': {'a': 1, 'b': 2, 'c': 3},'fourth': {'a': 1, 'b': 2, 'c': 3}}

for k, v in example.items():
    print(f"{k}: {v}")

output:

first: {'a': 1, 'b': 2, 'c': 3}
second: {'a': 1, 'b': 2, 'c': 3}
third: {'a': 1, 'b': 2, 'c': 3}
fourth: {'a': 1, 'b': 2, 'c': 3}
  • Related