Kumar
Kumar

Reputation: 314

Parse dictionary with Tuple as key

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

Upvotes: 1

Views: 588

Answers (3)

jamylak
jamylak

Reputation: 133634

>>> 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

Upvotes: 0

TobiMarg
TobiMarg

Reputation: 3807

  • (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
    

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142206

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

Upvotes: 0

Related Questions