Python Forum
Summing product of tuples inside a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Summing product of tuples inside a dictionary
#1
I'm having trouble figuring out how to implement this.
I have a dictionary with keyed touples. I would like to multiply the 2 touples and sum for every dictionary key.

I've created two classes. The first (ExampleBase) simply appends entries to the dictionary. The second (Useful) passes the appended dictionary and does the calculation.

I know I want a for loop to sum for all dictionary keys. I'm not sure how to access the touples within the dictionary to multiply them.

The code should do this: dictionary = {key1:(v1, v2), key2:(v1, v2), key3:(V1, v2)}
total = key1v1*key1v2 + key2v1*key2v2 + key3v1*key3v2

class ExampleBase:

    """
    This is the ExampleBase class
    """

    def __init__(self, company_name="N/A", stock_dict={}):
        """
        class constructor
        """
        self.company_name = company_name
        self.stock_dict = stock_dict
        print(self.stock_dict)       
        return
    
    def __str__(self):
        """
        Prints the company name string
        """        
        str = "The Company name is: %s" %\
            (self.company_name
            )
        
        return str
    
    
    def add_purchase(self, addtlSTK):
        """
        Adds item to stock_dict
        """
        self.stock_dict.update(addtlSTK)
        print(self.stock_dict)
        return


class Useful(ExampleBase):

    """
    Inherits from ExampleBase class
    """

    def __init__(self, company_name, stock_dict):
        super().__init__(name)
        return
    

    def compute_value(self, stock_dict):
        """
        Computes value of stk
        """
        stk_key=len(stock_dict)
        print(stk_key)
        for k, v in stock_dict():
            total =     
        return

##
## Program starts running from here
##
if __name__ == "__main__":
    a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)}
    b = ExampleBase("Bern", a)
    c = {"10-04-2014":(13, 14.25)}
    b.add_purchase(c)
    print(b)
    b.compute_value
Reply
#2
for example
>>> my_dict = {'a':(2,3), 'b':(4,5), 'c':(6,7)}
>>> sum(v1*v2 for v1,v2 in my_dict.values())
68

for tuple of any len or variable number of elements in tuple or if you want to be fancy for 2-element tuple

from functools import partial, reduce
from operator import mul

my_dict = {'a':(2,3,4), 'b':(4,5,6), 'c':(6,7,8)}
multiplication = partial(reduce, mul)
total = sum(map(multiplication, my_dict.values()))
print(total)
Reply
#3
@buran thanks! that totally works!

I've simplified the code and added your summation scheme. I believe I have a syntax error now?

class ExampleBase:
    def __init__(self, company_name="N/A", stock_dict={}):
        """
        class constructor
        """
        self.company_name = company_name
        self.stock_dict = stock_dict
        print(self.stock_dict)       
        return


class Useful(ExampleBase):
    """
    Inherits from ExampleBase class
    """
    def __init__(self, company_name, stock_dict):
        super().__init__(name)
        return
    

    def compute_value(self, stock_dict):
        """
        Computes value of stk
        """
        total_STK = sum(v1*v2 for v1,v2 in stock_dict.values())   
        return

##
## Program starts running from here
##
if __name__ == "__main__":
    a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)}
    b = ExampleBase("Bern", a)
    c = sum(v1*v2 for v1,v2 in a.values())
    print(c)
    b.compute_value(a)
Reply
#4
or
from functools import reduce
from operator import mul

my_dict = {'a':(2,3,4), 'b':(4,5,6), 'c':(6,7,8)}
total = sum(reduce(mul, value) for value in my_dict.values())
print(total)
Reply
#5
(Oct-15-2017, 09:11 PM)ijosefson Wrote: I believe I have a syntax error now?
is there any traceback? please post it in error tags.

NB - my post #4 is in addition to post #2, not suggestion to change your code
Reply
#6
Traceback: line 36
AttributeError: 'ExampleBase' object has no attribute 'compute_value'
Reply
#7
yes, that is because b is instance of class ExampleBase and this class has no method compute_value. if you want to use compute_value, b should be instance of Useful.
However there more problems that need to be fixed in your code, try to fix them yourself first
Reply
#8
Ok, got it to work.

Thank you!!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020