How to print a dictionary line by line in Python?

后端 未结 13 1504
情话喂你
情话喂你 2020-11-28 02:02

This is the dictionary

cars = {\'A\':{\'speed\':70,
        \'color\':2},
        \'B\':{\'speed\':60,
        \'color\':3}}

Using this

13条回答
  •  再見小時候
    2020-11-28 02:32

    Here is my solution to the problem. I think it's similar in approach, but a little simpler than some of the other answers. It also allows for an arbitrary number of sub-dictionaries and seems to work for any datatype (I even tested it on a dictionary which had functions as values):

    def pprint(web, level):
        for k,v in web.items():
            if isinstance(v, dict):
                print('\t'*level, f'{k}: ')
                level += 1
                pprint(v, level)
                level -= 1
            else:
                print('\t'*level, k, ": ", v)
    

提交回复
热议问题