How do you print a dictionary content in python?

A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:

def dumpclean(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print k
                dumpclean(v)
            else:
                print '%s : %s' % (k, v)
    elif isinstance(obj, list):
        for v in obj:
            if hasattr(v, '__iter__'):
                dumpclean(v)
            else:
                print v
    else:
        print obj

This produces the output:

A
color : 2
speed : 70
B
color : 3
speed : 60

I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.

import sys

def dump(obj, nested_level=0, output=sys.stdout):
    spacing = '   '
    if isinstance(obj, dict):
        print >> output, '%s{' % ((nested_level) * spacing)
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
        print >> output, '%s}' % (nested_level * spacing)
    elif isinstance(obj, list):
        print >> output, '%s[' % ((nested_level) * spacing)
        for v in obj:
            if hasattr(v, '__iter__'):
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
        print >> output, '%s]' % ((nested_level) * spacing)
    else:
        print >> output, '%s%s' % (nested_level * spacing, obj)

Using this function, the OP's output looks like this:

{
   A:
   {
      color: 2
      speed: 70
   }
   B:
   {
      color: 3
      speed: 60
   }
}

which I personally found to be more useful and descriptive.

Given the slightly less-trivial example of:

{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}

The OP's requested solution yields this:

test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)

whereas the 'enhanced' version yields this:

{
   test:
   [
      {
         1: 3
      }
   ]
   test3:
   {
      (1, 2):
      [
         abc
         def
         ghi
      ]
      (4, 5): def
   }
   test2:
   [
      (1, 2)
      (3, 4)
   ]
}

I hope this provides some value to the next person looking for this type of functionality.

Contents

  • Introduction
  • Print Dictionary as a Single String
  • Print Dictionary Key:Value Pairs
  • Print Dictionary Keys
  • Print Dictionary Values
  • Summary

To print dictionary items: key:value pairs, keys, or values, you can use an iterator for the corresponding key:value pairs, keys, or values, using dict.items(), dict.keys(), or dict.values() respectively and call print() function.

In this tutorial, we will go through example programs, to print dictionary as a single string, print dictionary key:value pairs individually, print dictionary keys, and print dictionary values.

To print whole Dictionary contents, call print() function with dictionary passed as argument. print() converts the dictionary into a single string literal and prints to the standard console output.

In the following program, we shall initialize a dictionary and print the whole dictionary.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}
print(dictionary)

Run

Output

{'a': 1, 'b': 2, 'c': 3}

To print Dictionary key:value pairs, use a for loop to traverse through the key:value pairs, and use print statement to print them. dict.items() returns the iterator for the key:value pairs and returns key, value during each iteration.

In the following program, we shall initialize a dictionary and print the dictionary’s key:value pairs using a Python For Loop.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}

for key,value in dictionary.items():
	print(key, ':', value)

Run

Output

a : 1
b : 2
c : 3

To print Dictionary keys, use a for loop to traverse through the dictionary keys using dict.keys() iterator, and call print() function.

In the following program, we shall initialize a dictionary and print the dictionary’s keys using a Python For Loop.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}

for key in dictionary.keys():
	print(key)

Run

Output

a
b
c

To print Dictionary values, use a for loop to traverse through the dictionary values using dict.values() iterator, and call print() function.

In the following program, we shall initialize a dictionary and print the dictionary’s values using a Python For Loop.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}

for value in dictionary.values():
	print(value)

Run

Output

1
2
3

Summary

In this tutorial of Python Examples, we learned how to print Dictionary, its key:value pairs, its keys or its values.

  • Add Item to Dictionary in Python
  • Python Example to Clear or Empty Dictionary
  • Python Create Dictionary
  • Python Nested Dictionary
  • Python Dictionary Length
  • Python Empty Dictionary

Can a dictionary be printed Python?

You can print a dictionary in Python using either for loops or the json module. The for loop approach is best if you want to display the contents of a dictionary to a console whereas the json module approach is more appropriate for developer use cases.

How do I print a dictionary value?

Python's dict. values() method can be used to retrieve the dictionary values, which can then be printed using the print() function.

How do I print a formatted dictionary in Python?

Use format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position. Python Dictionary can also be passed to format() function as a value to be formatted.

Can you print a key in dictionary Python?

To print the dictionary keys in Python, use the dict. keys() method to get the keys and then use the print() function to print those keys. The dict. keys() method returns a view object that displays a list of all the keys in the dictionary.