Home > Back-end >  I want to print output as 1 key 2 values pairs(dictionary) in python
I want to print output as 1 key 2 values pairs(dictionary) in python

Time:01-23

I've a code like this

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)

My input is

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

Output I'm getting

mobile 30 20

Know I want to convert this output as dictionary format(1 key & 2values as a list format)

Expected outputs.

{ 'mobile': [30,20] }

Can you guys suggest what is the logic can I use?~Thanks advance

CodePudding user response:

As @Andrey said, you can print it like so print({self.product_name: [self.market_price, self.quantity]}).

Don't use print though, as it won't actually be a dictionary output, only printed representation of a dictionary.

You would usually want to return the output using the return keyword:

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

That way you can use it later in the code:

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