簡體   English   中英

如何以它們所在的格式在字典中顯示鍵和值

[英]how to show both key and value in dictionary in the format they are in

我有一本像這樣的字典

mydict = { 'type': 'fruit', 'quantity': 20 }

我想按原樣只打印“type”字段,就像這樣 {'type': 'fruit'}

我在其他網站上找到了這個

class fruits(dict):
    def __str__(self):
        return json.dumps(self)
collect = [['apple','grapes']]
result = fruits(collect)
print(result)

沒有 jsonify 有沒有更簡單的方法? 我也試過 items() 方法,但它打印為(鍵,值),我不想讓它成為

如果你試圖定義一個行為與dict完全一樣的類,唯一的例外是它總是以特定方式打印,這可能是要走的路:

class subclass_of_dict(dict):
    def __str__(self):
        return "{'type' : " + f"'{self.get('type')}'" + '}'

使用這樣定義的類,您現在可以創建這個新類的幾個實例:

f1 = subclass_of_dict({'type' : 'fruit', 'quantity': 20})
f2 = subclass_of_dict({'type' : 'bowler hats', 'quantity': 13})

然后在這些實例上調用print會執行以下操作:

print (f1)
print (f2)

# result: 
    # {'type' : 'fruit'}
    # {'type' : 'bowler hats'}

這就是你想要的嗎?

這個很簡單。 您只需編寫幾行代碼。

class fruits(dict):
def __str__(self):
    return "{'type' : " + f"'{self.get('type')}'" + '}'

然后你只需要制作你的字典並打印出來。

mydict = fruits{ 'type' : 'fruit', 'quantity': 20 }
print(mydict)

我猜你已經找到了答案。 要以簡單的方式了解有關字典的更多信息,請遵循Python 字典

希望這條評論對你有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM