curious
curious

Reputation: 1554

What is the most appropriate python data structure to keep the result of pairwise computations over 2 dictionaries?

I have 2 dictionaries with long as the type of the values. I want to apply some computation at every possible combination of 2-values from the 2 dictionaries and maintain a data structure that will keep the result and the input values. i.e: key(a),value(a),key(b),value(b),f(value(a),value(b)) . What sort of data structures would you suggest for this operation enter image description here

Upvotes: 1

Views: 109

Answers (3)

phihag
phihag

Reputation: 288090

When your computation only depends on the values of the dictionary, you should reformulate your problem statement to take only an iterable of values, and not dictionaries.

You can use tuples as dictionary keys:

import itertools
Adict = {"x": 1, "y": 2, "z":3}
Bdict = {"foo": 4, "bar": 5, "baz":6}
A,B = Adict.values(),Bdict.values()
def comp(a, b):
  return a * b # Insert complicated computation here
res = {(a,b):comp(a,b) for a,b in itertools.product(A, B)}

Upvotes: 4

Sébastien
Sébastien

Reputation: 14831

I would suggest a dictionary with:

  • keys being tuples of tuples: ( (key(a), value(a)) , (key(b), value(b)) )
  • values being long (if it's the type returned by your function f(a,b))

Upvotes: 0

Silas Ray
Silas Ray

Reputation: 26160

Either a list of dicts or a more complex iterator defining your own custom object to represent the data and ways of iterating over the data by the different keys you have.

Upvotes: 1

Related Questions