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 objThis produces the output:
A color : 2 speed : 70 B color : 3 speed : 60I 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.
Print Dictionary as a Single String
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}Print Dictionary Key:Value Pairs
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 : 3Print Dictionary Keys
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 cPrint Dictionary Values
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 3Summary
In this tutorial of Python Examples, we learned how to print Dictionary, its key:value pairs, its keys or its values.
Related Tutorials
- 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