2

I have a dictionary dict which has two values per key, like so:

dict = {}
dict[name] = x1, x2

Let's say that this dictionary has 10 items in it. I would like to iterate over the keys of the dictionary such that I'm performing a calculation for each key-values set with respect to the other key-values sets in the dictionary. For instance, I would like to start at the first key and calculate something like x1_0 + x2_0 - x1_1 + x2_1, where "_0" denotes the first key's values and "_1" denotes the values associated with any other key's values. This calculation would be performed nine times with respect to all other nine keys. Then I would move to the second key-values set and perform the calculations with respect to the nine remaining keys, and so on.

I have tried doing this with two dictionaries containing the same data, but have been unsuccessful. Note that I've already done a float conversion for the values, so that is not the problem. Here is what I've tried:

for (name_0, (x1_0, x2_0)), (name_1, (x1_1, x2_1)) in zip(dict.iteritems(), dict2.iteritems()):
    if name_0 != name_1:
        d = x1_0 + x2_0 - x1_1 + x2_1
    print d
Daniel
  • 159
  • 1
  • 3
  • 9

2 Answers2

1

If my understanding is correct, you intend to perform a permutation of each of the couplet. With the resultant couplet pair, you would intend to perform some ad-hoc calculation

Let one of the Pair Pi be (Xi, Xj) where Xi is a couplet (Xi0, Xi1) then the formulation could be expressed as

def calc(x):
    return x[0][0] + x[0][1] - x[1][0] + x[1][1]

To create a pairwise permutation, you can use itertools.permutation as follows

permutations(_dict.values(), 2)

Now you just need to map the couplet pair with your formulated function

map(calc, permutations(d.values(), 2))
Abhijit
  • 62,056
  • 18
  • 131
  • 204
0

I ended up using indexing when initializing the for loop and this has worked very well:

for (dict.keys()[i], dict.values()[i]), (dict2.keys()[j], dict2.values()[j]) in zip(dict.iteritems(), dict2.iteritems()):
Daniel
  • 159
  • 1
  • 3
  • 9