在python3中打印嵌套字典

时间:2018-04-02 23:06:52

标签: python-3.x dictionary nested format

如何以特定格式打印嵌套的python字典? 所以,我的字典看起来像这样:

dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}

我尝试了以下方式:

for x, y in dictionary.items():
   print(x,":", y)

但它会打印L`

Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}

如何摆脱支架并打印明文信息?

希望以下列格式打印:

Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;

2 个答案:

答案 0 :(得分:2)

在你的情况下' y'是一个字典,所以如果你想以不同的方式打印它,你可以覆盖repr(对象的表示)或字典。 或者你可以在这里使用一些递归

self.entry = Entry(frame, textvariable=self.a_var)
self.label = Label(frame, textvariable=self.a_var)

答案 1 :(得分:1)

除非你的原始字典声明不是有效的python,除非每个单词都是一个已定义的变量,这似乎有效:

import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))

结果:

Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2