1

My dictionary with tuple as a key is as follows:

Key represents the x and y coordinates. (x, y)

D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
D2 = {(2, 8) : 67, (12, 10): 23, (14, 8): 56}

Now, from the above Dictionary, I would like to perform the following

  1. Sort dictionary D1 based on Keys
  2. Sort dictionary D2 based on Keys
  3. Simply, print the keys and values in D1
  4. Simply, print the keys and values in D2
  5. Then do the following:

(pseudocode)

total = 0
For each key (x, y) in D1,  
   if D2.has_key((y, x)):
      total = total + D1[(x, y)] * D2[(y, x)]
   Print total
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Kumar
  • 314
  • 3
  • 5
  • 16

3 Answers3

1
  • (1/2) To sort a dict you have to use collections.OrderedDict (because normal dicts aren't sorted) Code:

    from collections import OrderedDict
    D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
    D1_sorted = OrderedDict(sorted(D1.items()))
    
  • (3/4) Code: print(D1)

  • (5) convert your code to python

    total = 0
    for x, y in D1.keys():
        try:
            total = total + D1[(x, y)] * D2[(y, x)]
        except KeyError:
            pass
    print total
    
TobiMarg
  • 3,667
  • 1
  • 20
  • 25
0

I think you're after (for your pseudo-code):

D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
D2 = {(2, 8) : 67, (12, 10): 23, (14, 8): 56}

total = sum(D1[k] * D2.get(k[::-1], 0) for k in D1.iterkeys())
# 3049
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0
>>> from collections import OrderedDict
>>> D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
>>> D2 = {(2, 8) : 67, (12, 10): 23, (14, 8): 56}
>>> D1 = OrderedDict(sorted(D1.items()))
>>> D2 = OrderedDict(sorted(D2.items()))
>>> print D1
OrderedDict([((8, 14), 45), ((10, 12), 23), ((12, 9), 29)])
>>> print D2
OrderedDict([((2, 8), 67), ((12, 10), 23), ((14, 8), 56)])
>>> sum(D1[(x, y)] * D2.get((y, x), 0) for x, y in D1)
3049
jamylak
  • 128,818
  • 30
  • 231
  • 230