如何以特定格式打印嵌套的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;
答案 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