【问题标题】:I want to print output as 1 key 2 values pairs(dictionary) in python我想在python中将输出打印为1键2值对(字典)
【发布时间】:2022-01-22 09:38:34
【问题描述】:

我有这样的代码

class salesperson:
    
    def __init__(self, name):
        self.name=name
        
        
    def buyproduct(self, product_name, market_price, quantity):
        self.product_name = product_name
        self.market_price=market_price
        self.quantity=quantity
        
        print(self.product_name, self.market_price, self.quantity)
        
        
    def getname(self):
        print(self.name)

我的意见是

sp_name=salesperson('name')
sp_name.buyproduct('mobile',30,20)

我得到的输出

mobile 30 20

知道我想将此输出转换为字典格式(1 个键和 2 个值作为列表格式)

预期输出。

{ 'mobile': [30,20] }

你们能建议我使用什么逻辑吗?~谢谢提前

【问题讨论】:

  • 打印({self.product_name: [self.market_price, self.quantity]})

标签: python class


【解决方案1】:

正如@Andrey 所说,您可以像这样打印它print({self.product_name: [self.market_price, self.quantity]})

不要使用 print,因为它实际上不是字典输出,只是字典的打印表示。

您通常希望使用 return 关键字返回输出:

return {self.product_name: [self.market_price, self.quantity]}

这样你就可以在后面的代码中使用它:

sp_name=salesperson('name')
output = sp_name.buyproduct('mobile',30,20)
# Do stuff with output
print(output) # Print it if you wish.

【讨论】:

    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多