These answers are good if you want to print the entire json/dict. However, there are times when you only want the "outline", since the values are too long. In this case you can use this:
def print_dict_outline(d, indent=0):
for key, value in d.items():
print(' ' * indent + str(key))
if isinstance(value, dict):
print_dict_outline(value, indent+2)
elif isinstance(value, list) and all(isinstance(i, dict) for i in value):
if len(value) > 0:
keys = list(value[0].keys())
print(' ' * (indent+2) + 'dict_list')
for k in keys:
print(' ' * (indent+4) + str(k))
# Example dictionary with a list of dictionaries
my_dict = {
'a': {
'b': [
{'c': 1, 'd': 2},
{'c': 3, 'd': 4}
],
'e': {
'f': 5
}
},
'g': 6
}
# Print the outline of the dictionary
print_dict_outline(my_dict)
The output is:
a
b
dict_list
c
d
e
f
g
In this implementation, if the value of a dictionary key is a list of dictionaries, we first check if the list has any elements. If it does, we define the keys of the first dictionary in the list, and print them as subheadings of 'dict_list'. We do not print the values for each dictionary in the list, only the keys. This allows us to print an outline of the nested dictionary that includes subheadings for each list of dictionaries, without printing the individual values of each dictionary.
pprint?r.json()), so it's just a Python data structure after that. So what exactly do you want to pretty print? Python data structures or JSON?