如何打印包含多个列表和字典的嵌套字典?

2024-09-28 19:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

[[{'text': '\n     ', 'category': 'cooking', 'title': {'text': 'Everyday 
  Italian', 'lang': 'en'}, 'author': {'text': 'Giada De Laurentiis'}, 'year': 
  {'text': '2005'}, 'price': {'text': '30.00'}}, 
  {'text': '\n     ', 'category': 'children', 'title': {'text': 'Harry Potter', 
  'lang': 'en'}, 'author': {'text': 'J K. Rowling'}, 'year': {'text': 
  '2005'}, 'price': {'text': '29.99'}}, {'text': '\n     ', 'category': 
  'web', 'title': {'text': 'XQuery Kick Start', 'lang': 'en'}, 'author': 
  [{'text': 'James McGovern'}, {'text': 'Per Bothner'}, {'text': 'Kurt 
  Cagle'}, {'text': 'James Linn'}, {'text': 'Vaidyanathan Nagarajan'}], 
  'year': {'text': '2003'}, 'price': {'text': '49.99'}}, {'text': '\n     ', 
  'category': 'web', 'cover': 'paperback', 'title': {'text': 'Learning XML', 
  'lang': 'en'}, 'author': {'text': 'Erik T. Ray'}, 'year': {'text': '2003'}, 
  'price': {'text': '39.95'}}]]

输出格式:

category : cooking,
title : ['Everyday Italian', 'lang': 'en'],
author : Giada De Laurentiis,
year : '2005',
price : '30.00'

category : children,
title : ['Harry Potter', 'lang': 'en'],
author : 'J K. Rowling',
year : '2005',
price : '29.99'

category : web,
title : [ 'XQuery Kick Start''lang': 'en'],
author :[ 'James McGovern' , 'Per Bothner','Kurt Cagle','James Linn', 'Vaidyanathan Nagarajan'],
year :  '2003',
price :  '49.99'

category : web,
cover : paperback,
title : [ 'Learning XML','lang': 'en'],
author : 'Erik T. Ray',
year :  '2003',
price : '39.95'

Tags: textweblangtitledeyearpriceauthor
3条回答
def printBook(d):
    del d['text']
    for i in d:
        if type(d[i]) == dict:
            if len(d[i])==1:
                d[i] = list(d[i].values())[0]
            else:
                d[i] = [('' if j=='text' else (j+':')) + d[i][j] for j in d[i]]
    s = '\n'
    for i,j in d.items():
        s += f' {i} : {j} ,\n'

    print(s)

试试这些,它会将单个词典打印成您描述的格式

看看pprint模块,它提供了一种打印数据结构的好方法,无需编写自己的格式化程序

下面这样一个简单的循环应该可以得到所需的输出

for entry in data[0]:
    for k, v in entry.items():
        print(k, ':', v)

相关问题 更多 >