繁体   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