python - 以元组为键解析字典

标签 python tuples

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

键代表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. 根据键对字典 D1 进行排序
  2. 根据键对字典 D2 进行排序
  3. 简单地,打印 D1 中的键和值
  4. 简单地,打印 D2 中的键和值
  5. 然后执行以下操作:

(伪代码)

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/

相关文章:

python - 将 dict 应用到 ndarray 的快速(非循环)方法是什么(意味着使用元素作为键并替换为值)

haskell - 将列表拆分为可能的元组列表

python - Pandas 和元组检查

scala - 如何基于元组第一个元素进行总结?

python - NumPy 数组大小问题

python - 值错误 : Could not interpret input 'index' when using index with seaborn lineplot

python - 在pygame中按多次键来移动图像

python - 如何转换时间范围(19 :00-20:00) to a TimeStamp/Date Time object?

python - 将元组分配给 pandas 中的单元格

python - 计算两个元组列表之间匹配的第二个元素的数量的更快方法? - Python