4 回答

TA貢獻1785條經驗 獲得超8個贊
或者,您可以創(chuàng)建自己的對象:
class NicelyPrintingDict():
def __init__(self, some_dictionary):
self.some_dictionary = some_dictionary
def __str__(self):
s = ''
for key, value in self.some_dictionary.items():
s += key + ': ' + str(value) + ' '
return s.strip()
然后,按如下方式使用它:
foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}
nice_foo = NicelyPrintingDict(foo)
print(nice_foo)

TA貢獻1818條經驗 獲得超11個贊
您可以刪除所有不需要的字符,然后根據需要打印它,如下所示:
foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'} print (str(foo).replace("{","").replace("'","").replace("}",""))
輸出:
a: 123, b: asdf, c: Hello, world!
注意,只要字符{
,}
或'
是字典的一部分,該解決方案就會失敗
更詳細地 - 當調用str
函數時 - 每個對象都可以實現__str__
返回字符串的函數(您可以為自定義類自己實現它)。當利用它時 - 從函數返回的 str 可以被視為任何其他字符串并替換您想要的任何內容。

TA貢獻1784條經驗 獲得超9個贊
如果你知道你一直在使用哪些字段,你可以這樣做:
foo = {
'a': 123,
'b': 'asdf',
'c': 'Hello, World!'
}
print(f"a: {foo['a']} b: {foo['b']} c: {foo['c']}")
a:123 b:asdf c:你好,世界!

TA貢獻1801條經驗 獲得超8個贊
foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}
for i,j in foo.items():
print(i, ":", j, end = ",")
a : 123, b : asdf, c : Hello, world!,
添加回答
舉報