我的以元组为键的字典如下:
键代表x和y坐标。 (x,y)
D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
D2 = {(2, 8) : 67, (12, 10): 23, (14, 8): 56}
现在,从上面的词典中,我想执行以下操作
- 根据键对字典 D1 进行排序
- 根据键对字典 D2 进行排序
- 简单地,打印 D1 中的键和值
- 简单地,打印 D2 中的键和值
- 然后执行以下操作:
(伪代码)
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
最佳答案
(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
关于python - 以元组为键解析字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16776806/