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
4

3 回答 3

1
  • (1/2)要对您必须使用的collections.OrderedDict字典进行排序(因为未对普通字典进行排序)代码:

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

  • (5) 将你的代码转换成python

    total = 0
    for x, y in D1.keys():
        try:
            total = total + D1[(x, y)] * D2[(y, x)]
        except KeyError:
            pass
    print total
    
于 2013-05-27T16:26:18.900 回答
0

我想你在(对于你的伪代码):

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
于 2013-05-27T16:16:19.377 回答
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
于 2013-05-27T20:22:47.073 回答