以元组为键解析字典

时间:2013-05-27 15:58:30

标签: python tuples

我的字典以元组为关键字如下:

Key表示x和y坐标。 (x,y)

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

现在,从上面的词典中,我想执行以下内容

  1. 根据键
  2. 对字典D1进行排序
  3. 根据键
  4. 对字典D2进行排序
  5. 只需在D1
  6. 中打印键和值即可
  7. 只需在D2
  8. 中打印键和值即可
  9. 然后执行以下操作:
  10. (伪代码)

    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
    

3 个答案:

答案 0 :(得分: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
    

答案 1 :(得分: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

答案 2 :(得分: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